【问题标题】:Unable to push data into current object inside mongo database无法将数据推送到 mongo 数据库中的当前对象
【发布时间】:2016-09-13 10:27:44
【问题描述】:

我正在使用 mongodb native 和 Node.js 6.5.0。

我在 mongodb 中有用户对象,其结构如下:

{ 
    "_id" : ObjectId("57d7d294d96a73d128c46db9"), 
    "id" : "105862592064", 
    "labels" : [

    ]
}

我有一个循环(对于找到的每个用户)从 API 获取数据,然后将其推送到数组类型的对象属性中。其中用户 ID user.id 和要推送的数据是 resp.labels

这是我的代码:

db.collection('users').update(
          {"id":user.id},
          {"$push":{"users.labels":resp.labels}}
)

它不返回任何错误,也不更新对象。我做错了什么?

【问题讨论】:

  • db.collection('users').update( { _id: user.id, labels: [] }, { $set: { "labels.$" : resp.labels } } ) 试试有了这个

标签: javascript node.js mongodb node-mongodb-native


【解决方案1】:
Try this:

db.collection('users').update(
          {"id":user.id},,
           {
             $push: {
               labels: {
                  $each: //yourArray
               }
             }
           }
        );

【讨论】:

    【解决方案2】:

    $push 用于将单个元素推送到数组中。使用$push$each 一起推送多个元素。此外,对象标签周围的引号不应是必需的:

    db.collection('users').update(
          { id:user.id },
          { $push: { labels: { $each: resp.labels } } }
    )
    

    【讨论】:

      【解决方案3】:

      试试$set

      db.collection('users').update(
            {"id":user.id},
            {$set:{"users.labels":"hola"}})
      

      【讨论】:

        【解决方案4】:

        尝试包含{upsert:true}

        db.collection('users').update(
                  {"id":user.id},
                  {"$push":{"users.labels":resp.labels}},
                  {"upsert": true}
        );
        

        如果新值不存在,Upsert 插入新值。

        【讨论】:

        • 但是,有一个问题。它创建名为 users 的新属性,并在该 users 对象中创建包含标签的标签对象。
        猜你喜欢
        • 2019-02-11
        • 1970-01-01
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多