Mongoose - FindOne and Search inside and Array



在我的用户集合中,我在一个数组中存储了一组愿望列表项,如下所示

{
"_id" : ObjectId("61840f03cfd5c0b680648f2c"),
"email" : "xxxxxx@domain.com",
"wishlist" : [ 
ObjectId("6182a45f38f323f21bec2ddc"), 
ObjectId("61825f026d0fd99ef70380fd")
]
}

在我的React Product页面中,我想根据电子邮件和愿望列表数组中保存的objectID(即6182a45f38f323f21bec2ddc(,检查产品是否已添加到愿望列表中。

尽管如此,我还是不明白如何使用mongoose编写查询。

我想出的最好的解决方案是

db.getCollection('users').find({
email: "xxxxxx@domain.com",
"user.wishlist" : "6182a45f38f323f21bec2ddc",

}).select('wishlist').exec()

但结果我得到了一个空数组。如果找到产品,我想返回产品的objectId。我如何明确告诉猫鼬选择与特定电子邮件地址匹配的文档,然后映射到愿望列表数组的每个元素中,以找到匹配的产品?

为了清楚起见,下面是我的用户模型

const userSchema = new mongoose.Schema({
email:{
type:String,
required: true,
index: true,
},
wishlist:[{type:ObjectId, ref:"Product"}],
},
{timestamps: true}
);

谢谢你们的帮助!

问题是您的查询是错误的。您正在尝试查找user.wishlist,但在您的模式中,该字段仅为wishlist

所以你需要这个查询:

db.getCollection('users').find({
email: "xxxxxx@domain.com",
"wishlist" : "6182a45f38f323f21bec2ddc"
}).select('wishlist').exec()

示例

此外,我认为mongoose会自动将字符串解析为ObjectId,但可能需要像这样使用mongoose.Types.ObjectId()

db.getCollection('users').find({
email: "xxxxxx@domain.com",
"wishlist" : mongoose.Types.ObjectId("6182a45f38f323f21bec2ddc")
}).select('wishlist').exec()

至少,如果我已经理解了这个问题,那么可以在执行后使用像本例这样的投影阶段来避免map,只获取与值匹配的元素。

db.getCollection('users').find({
email: "xxxxxx@domain.com",
"wishlist" : "6182a45f38f323f21bec2ddc"
},
{
"wishlist.$": 1
}).select('wishlist').exec()

最新更新