在我的用戶集合中,我將一組愿望清單專案存盤在一個陣列中,如下所示
{
"_id" : ObjectId("61840f03cfd5c0b680648f2c"),
"email" : "[email protected]",
"wishlist" : [
ObjectId("6182a45f38f323f21bec2ddc"),
ObjectId("61825f026d0fd99ef70380fd")
]
}
在我的 React 產品頁面中,我想根據電子郵件和保存在愿望清單陣列((即 6182a45f38f323f21bec2ddc)中的 objectID 來檢查產品是否已添加到 wishlist。
盡管付出了努力,我還是不明白如何使用貓鼬撰寫查詢。
我想出的最佳解決方案是
db.getCollection('users').find({
email: "[email protected]",
"user.wishlist" : "6182a45f38f323f21bec2ddc",
}).select('wishlist').exec()
但結果我得到了一個空陣列。如果找到產品,我想回傳產品的 objectId。我如何明確告訴 mongoose 選擇與特定電子郵件地址匹配的檔案,然后映射到 Wishlist 陣列的每個元素中以找到匹配的產品?
為了清楚起見,下面是我的用戶模型
const userSchema = new mongoose.Schema({
email:{
type:String,
required: true,
index: true,
},
wishlist:[{type:ObjectId, ref:"Product"}],
},
{timestamps: true}
);
謝謝你們的幫助!
uj5u.com熱心網友回復:
問題是您的查詢是錯誤的。您正在嘗試查找,user.wishlist但在您的架構中,該欄位僅為wishlist.
所以你需要這個查詢:
db.getCollection('users').find({
email: "[email protected]",
"wishlist" : "6182a45f38f323f21bec2ddc"
}).select('wishlist').exec()
示例在這里
另外,我認為貓鼬會自動將字串決議為ObjectId但可能需要mongoose.Types.ObjectId()像這樣使用:
db.getCollection('users').find({
email: "[email protected]",
"wishlist" : mongoose.Types.ObjectId("6182a45f38f323f21bec2ddc")
}).select('wishlist').exec()
至少,如果我已經理解了這個問題,您可以避免map在執行之后使用投影階段(如本例)來僅獲取與值匹配的元素。
db.getCollection('users').find({
email: "[email protected]",
"wishlist" : "6182a45f38f323f21bec2ddc"
},
{
"wishlist.$": 1
}).select('wishlist').exec()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/361382.html
