我正在使用aggregate([...])方法從 MongoDB 中選擇檔案,但是我有一個問題$lookup,查詢后我無法獲得參考欄位的結果info,它不起作用,因為它總是回傳空陣列。我怎么解決這個問題 ?
我的 MongoSchema 配置:
const PostModel = new Schema({
...,
info: [
{
label: {
type: ObjectId,
ref: 'catalogs',
required: true
},
value: {
type: ObjectId,
ref: 'attributes',
required: true
}
}
],
...
})
我的執行聚合到查詢集合的代碼:
const doc = await PostModel.aggregate([
{
"$lookup": {
"from": "catalogs",
"localField": "info.label",
"foreignField": "_id",
"as": "infoLabel"
}
},
{
"$lookup": {
"from": "attributes",
"localField": "info.value",
"foreignField": "_id",
"as": "infoValue"
}
},
{
"$project": {
info: {
label: '$infoLabel',
value: '$infoValue'
}
}
}
])
console.log(doc) // it always return empty array :(
uj5u.com熱心網友回復:
您需要先展開資訊,然后使用可以作業的查找查詢
{ $unwind:"$info" },
{ $lookup:{ ... } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424012.html
