简体   繁体   中英

update empty array fields in mongodb

I am trying to update my array which has fields in it. The array is already saved in the database, but without the fields in it. Is there a way to update the empty array and add fields in it

Schema

      const UserSchema = new Schema({
        User: [{

         Name:{
           type: String,
        },

        Email:{
           type: String,
        },

       }]
    })
      

The array is already saved in the database but its empty like this

saved database

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

Here is the code i used to update the array

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

Every time I run the code the array doesn't update, does anyone know how to go about this problem?

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

Update array using $each . And User should be capital as fields are case sensitive in mongo.

Refer

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM