【问题标题】:Updating Nested subdocument using id mongoose使用 id mongoose 更新嵌套子文档
【发布时间】:2016-08-11 00:17:57
【问题描述】:

我需要编辑我的处方数量。这是我的示例代码。

collection.update(
{ "_id" : 1,"medications._id" : 23,"medications.prescriptions._id":77 },
{ $set : { "medications.$0.prescriptions.$1.quantity" : 30 } },
false,
true
)

如何编辑。它没有显示任何错误。

【问题讨论】:

  • 尝试药物。$.prescriptions.$.quantity
  • 嗨chirag 。我收到以下错误“在路径 'medications.$.prescriptions.$.quantity' 中找到太多位置(即'$')元素”。

标签: node.js mongoose


【解决方案1】:

相反,您可以遵循更多easy to understand 的方式。

var updateData = {
    medications.prescriptions.quantity: 0
}

collection.update({ "_id" : 1,"medications._id" : 23,"medications.prescriptions._id":77 }, updateData, function(err, response){
    if(err){
        res.json(err);
    }
    //your success handler
});

【讨论】:

  • 嗨 Ajitej,它会删除我的子文档,并将药物处方设置为 0。
  • 我已经稍微编辑了答案,根据我的假设,您的子文档看起来像 medications: {prescriptions: {quantity: //value }}
  • 它会在您上面编辑的代码上抛出“Unexpected token .”
  • 兄弟,你能分享一下模型并详细解释一下你想要的回应是什么!
  • 下面是我的 json 数据。 “_id”:54,“标题”:“p1”,“药物”:[{“_id”:57,“标题”:“S1”,“处方”:[{“_id”:57a,“标题”: "T1", "description" : "T1" }, { "_id" : 4507, "title" : "T12", "description" : "T12121212" } ] },在这里我想编辑我的处方详情。你还好吗
【解决方案2】:

您只能使用一个位置运算符

并查看此文档:

https://docs.mongodb.com/manual/reference/operator/update/positional/

【讨论】:

  • 嗨chirag 。我收到以下错误“在路径 'medications.$.prescriptions.$.quantity' 中找到太多位置(即'$')元素”。
  • 你能提供你的json数据吗?
  • 当然。下面是我的 json 数据。 {“_id”:ObjectId(“57ab0f1627687f811900000d”),“title”:“Primary”,“bgimage”:“2016-05-25 10:56:16.png 的截图”“medications”:[{“_id”: ObjectId("57ab0f2227687f811900000e"), "title" : "Secondary" "prescriptions" : [ { "_id" : ObjectId("57ab0f3227687f811900000f"), "title" : "Tertiary", "description" : "Desc" } ] } ] , }
  • 在您的 collection.update 中,尝试drugs[0]._id 和drugs[0].prescriptions[0]._id
  • 您要求我更改药物指数(即 [0] )。但同样的错误只发生“在路径中找到太多位置(即'$')元素”
【解决方案3】:

我遇到了同样的问题,因为数组更新中的 as 数组需要很大的性能影响。所以,mongo db 不支持它。重新设计您的数据库,如下面的链接所示。


https://pythonolyk.wordpress.com/2016/01/17/mongodb-update-nested-array-using-positional-operator/

【讨论】:

    猜你喜欢
    • 2021-03-26
    • 1970-01-01
    • 2018-09-04
    • 2016-10-06
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2017-08-13
    相关资源
    最近更新 更多