【问题标题】:Mongoose - FindOne and Search inside and ArrayMongoose - FindOne 和 Search inside 和 Array
【发布时间】:2021-12-30 09:15:34
【问题描述】:

在我的用户集合中,我将一组愿望清单项目存储在一个数组中,如下所示

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

在我的 React 产品页面中,我想根据电子邮件以及保存在愿望清单数组中的 objectID((即 6182a45f38f323f21bec2ddc)来检查产品是否已添加到愿望清单中。

尽管付出了很多努力,但我还是不明白如何使用 mongoose 编写查询。

我想出的最佳解决方案是

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

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

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

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

感谢你们的帮助!

【问题讨论】:

    标签: reactjs json mongodb mongoose


    【解决方案1】:

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

    所以你需要这个查询:

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

    例如here

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

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

    至少,如果我理解了这个问题,您可以在执行后使用 this example 之类的投影阶段避免 map,以仅获取与该值匹配的元素。

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

    【讨论】:

    • 您好 J.F. 这是正确的解决方案!你的理解是完美的!谢谢
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2018-06-09
    • 2017-12-08
    • 2020-08-31
    • 2015-10-26
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多