首页 > 解决方案 > 当我不知道文档 ID 时如何使用 mongoose 查询子文档

问题描述

我的任务是使用 mongo db 重建一个更单一的数据库。在这个数据库中,我有一个看起来像这样的产品文档。

{
  product_id: 4.
  questions: [
    {
      question_id: 10,
      question_text: "hello?",
      helpfulness: 0
    },
    {
      question_id: 11,
      question_text: "goodbye?",
      helpfulness: 1
    }
  ]
}

我将收到对我的服务器的请求,其中包含 question_id(即 11),我需要增加问题的帮助。我到处寻找,但似乎找不到一种方法来仅使用问题 ID 来查询我的数据库并在不知道产品 ID 的情况下更新该问题。有没有办法做到这一点?非常感谢您的帮助!

标签: javascriptmongodbmongoose

解决方案


给你,首先你需要匹配问题ID,然后将相对有用性增加1。试试这个

db.collection.updateOne({'questions.question_id' : 11}, {$inc : {"questions.$.helpfulness" : 1}})

输出 :

{ 
    "_id" : ObjectId("5f891ca72857d128c68bf01a"), 
    "product_id" : 4.0, 
    "questions" : [
        {
            "question_id" : 10.0, 
            "question_text" : "hello?", 
            "helpfulness" : 0.0
        }, 
        {
            "question_id" : 11.0, 
            "question_text" : "goodbye?", 
            "helpfulness" : 2.0
        }
    ]
}

推荐阅读