[英]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.