我有一个疑问,我希望执行类似的操作:
中
下面是我的理解尝试过的
let docs = await Document.find({ archive: { $exists: false }})
.and([{ owner_email: { $regex: localQuery } }])
.or()
.populate('owner_id', null, {
email: { $regex: localQuery },
});
所以我想做的是,我有两个模式,用户和文档,用户有时作为图书管理员共享,然后我希望返回,两者都匹配填充的电子邮件或实际所有者的电子邮件。
发布于 2021-06-01 09:59:40
由于猫鼬的populate()
方法并不真正“连接”集合,而是在find()
操作之后对数据库进行另一个查询以填充,因此您可以切换到聚合管道并使用$lookup
来匹配引用字段中的电子邮件。因此,假设你的模型看起来像:
const Document = mongoose.model('Document', {
name: String,
archive: String,
owner_email: String,
owner: {type: Schema.Types.ObjectId, ref: 'Person'}
});
const Person = mongoose.model('Person', {
firstName: String,
lastName: String,
email: String
});
然后,你可以:
const result = await Document.aggregate([
{
$lookup: {
from: Person.collection.name,
localField: "owner",
foreignField: "_id",
as: "referencedOwner"
}
},
{
$match: {
archive: {$exists: false},
$or: [
{"referencedOwner.email": {$regex: localQuery}},
{"owner_email": {$regex: localQuery}}]
}
}
]);
下面是蒙古操场上的一个工作示例:https://mongoplayground.net/p/NqAvKIgujbm
https://stackoverflow.com/questions/67785649
复制相似问题