首页 > 解决方案 > 更新 mongodb 中的空数组字段

问题描述

我正在尝试更新其中包含字段的数组。该数组已保存在数据库中,但其中没有字段。有没有办法更新空数组并在其中添加字段

架构

      const UserSchema = new Schema({
        User: [{

         Name:{
           type: String,
        },

        Email:{
           type: String,
        },

       }]
    })
      

该数组已保存在数据库中,但它像这样为空

保存的数据库

      "id": 101,
      "User":[], 

这是我用来更新数组的代码

           User.update({id: 101,},
             {
             $push:{
                 user:{
                      Name: "Kevin",
                      Email: "Kevin@gmail.com",
                     },
                   }
             },(err, data)=>{
                console.log(data)
             })

每次我运行代码时数组都不会更新,有谁知道如何解决这个问题?

标签: javascriptarraysmongodb

解决方案


db.getCollection('test2').update({
  "id": 101
},
{
  $push: {
    User: {
      $each: [
        {
          "name": "gibbs"
        }
      ]
    }
  }
})

使用 更新数组$each。并且User应该是大写,因为字段在 mongo 中区分大小写。

参考

输出:

/* 1 */
{
    "_id" : ObjectId("5f08753ce96d8884b6bcc92e"),
    "id" : 101,
    "User" : [ 
        {
            "name" : "gibbs"
        }
    ]
}

推荐阅读