[英]Query the fields in 3 different nested arrays in same document in Mongoose?
下面是我的模式設計
const Schema1 = mongoose.Schema({
_id: false,
id: { type: mongoose.Schema.Types.ObjectId,
ref: 'UserinfoSchema'
},
name: { type: String , default: null },
from: { type: Date, default: Date.now }
})
const ProfileSchema = mongoose.Schema({
profilename:{
type: String,
required: true
},
list:{
acceptedList:[ Schema1 ],
requestedList:[ Schema1 ],
pendingList:[ Schema1 ]
}
})
我想建立一個查詢,該查詢在所有嵌套的數組(即acceptedList,requestedList,pendingList)中進行查詢,並找出id是否存在,如果id在任何列表中都不存在,則更新請求的列表。
任何一種技術都是有幫助的。 性能是關鍵。
您可以使用$or
運算符執行此操作:
db.Collection.update({
$or: {
"list.acceptedList": {$nin: [your_id]},
"list.requestedList": {$nin: [your_id]},
"list.pendingList": {$nin: [your_id]}
}
}, {
$addToSet: {
"list.requestedList": your_id
}
});
帶[your_id]的$nin
運算符檢查您的ID是否不在3個數組中,您必須使用[],因為它僅允許使用數組。
因此,在您的JavaScript代碼中,當用戶接受請求時,您可以使用此查詢(您必須先獲取要插入到acceptedList中的數據):
db.Collection.update({
_id: collection_id,
"list.requestedList": request_id
}, {
$pull: {
"list.requestedList": your_id // I re use what i give to you
},
$addToSet: {
"list.acceptedList": your_id // or what you want
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.