【问题标题】:Update an Object in an array which is inside an Object更新对象内的数组中的对象
【发布时间】:2018-06-30 02:54:30
【问题描述】:

新手帮助! 我需要帮助更新对象中包含的数组中的值!

{ "_id" : ObjectId("5a641fc1b66d0a1b7c274c99"),
  "comments" : [ { "author" : { "id" : ObjectId("5a5c93954c5b6f35953d38e0"), 
                  "username" : "Anton" },
                  "_id" : ObjectId("5a641fceb66d0a1b7c274c9a"),
                  "text" : "I love this place!", "__v" : 0 },

                { "author" : { "id" : ObjectId("5a5c93954c5b6f35953d38e0"), 
                  "username" : "Anton" }, 
                  "_id" : ObjectId("5a642023b66d0a1b7c274c9b"),
                  "text" : "Supercool!", "__v" : 0 } ],

  "campGroundName" : "Desert Creek",
  "campGroundImage":
                "https://farm8.staticflickr.com/7205/7121863467_eb0aa64193.jpg",
  "description" : "  Donec rhoncus, enim vel semper pharetra, dui justo accumsan neque, nec dictum tortor nibh id es", "__v" : 2,
  "addedBy" : { "id" : ObjectId("5a5c93954c5b6f35953d38e0"), "username" : "Anton" } }`

这里我要访问对象的cmets数组中text的值..

如何更新 Mongoose 中文本的值??

提前致谢!

【问题讨论】:

  • 你想更新所有的 cmets,或者任何特定的评论?
  • 一个特定的评论单独使用它的 ObjectId
  • 进入你的父对象,然后用它搜索特定的评论;评论id,或者直接提供评论id搜索,使用findOneAndUpdate。 :)
  • 我尝试了所有我能用我所有的力量做的事情,但没有进展..我做不到:(
  • 试试.update({"_id" : ObjectId("5a641fc1b66d0a1b7c274c99"), "comments._id": ObjectId("5a641fceb66d0a1b7c274c9a")}, {$set:{"comments.$.text":"some new text"}});

标签: arrays node.js mongodb mongoose


【解决方案1】:

使用 $elemMatch 进行查找查询以在嵌套数组中进行搜索,然后使用“myarrayfield.$.keyoftheobjectinarray”进行更新:

在匹配 u == 1 的嵌套对象数组中用 10 更新所有 u 键的示例

db.a.update({"a": {$elemMatch:{"u": 1}}},{$set:{"a.$.u": 10}},{multi: true, upsert:false})

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 2018-09-27
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多