[英]How to perform FIND, then perform AND, then perform OR with POPULATE in Mongoose
我有一个查询,我希望执行类似的操作:
根据我的理解,以下是我尝试过的
let docs = await Document.find({ archive: { $exists: false }})
.and([{ owner_email: { $regex: localQuery } }])
.or()
.populate('owner_id', null, {
email: { $regex: localQuery },
});
所以我想要做的是,我有两个模式,用户和文档,用户有时与 [作为图书管理员] 共享,然后我希望返回,两者都匹配填充的 email 或实际所有者的 email。
由于 mongoose 的populate()
方法并没有真正“加入” collections 而是在find()
操作后对数据库进行另一个查询以填充,因此您可以切换到聚合管道并使用$lookup
以匹配引用中的 email场地。 所以假设你的模型看起来像:
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}}]
}
}
]);
这是 mongoplayground 上的一个工作示例: https://mongoplayground.net/p/NqAvKIgujbm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.