我有一个查询,我希望执行类似的操作:
- 存档不存在AND
- 架构中的所有者电子邮件在查询OR中
- Populated架构中的所有者电子邮件处于查询中
以下是我在理解时所做的尝试
let docs = await Document.find({ archive: { $exists: false }})
.and([{ owner_email: { $regex: localQuery } }])
.or()
.populate('owner_id', null, {
email: { $regex: localQuery },
});
所以我想做的是,我有两个模式,用户和文档,用户有时会被共享[作为图书管理员],然后我希望返回,两者都匹配填充的电子邮件或实际所有者的电子邮件。
因为猫鼬的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}}]
}
}
]);
以下是mongoplayground上的一个工作示例:https://mongoplayground.net/p/NqAvKIgujbm