简体   繁体   中英

mongoDB: adding and updating some fields in a (nested) object

This is a mongoDB document, to which I need to add some data:

{
    "_id" : "7KufvMQFyyeuKFP68",
    "target" : {
        "10" : "true",
        "id" : "ePce6fBAHx9KeKjuM"
    }
}

I need to update existing fields in target or add them, if they do not exist. This is what I tried:

var result = { "30": "true", "id" : "ePce6fBAHx9KeKjuM" };

Collection.upsert(
    { _id: id }, 
    { $set: { target: result } }
);

But with this 10 is replaced by 30 , but I expect this result:

{
    "_id" : "7KufvMQFyyeuKFP68",
    "target" : [{
        "10" : "true",
        "30" : "true",
        "id" : "ePce6fBAHx9KeKjuM"
    }]
}

It seems that you want an array of objects to be updated. The array is your target field so make sure the type is an array in your schema. To update the array select the array by the id or field of your choice.

This code finds the field and adds the "30" : "true", and leaves the other information in the object inside an array. Hope it helps.

var userSchema = new mongoose.Schema({
    name: String,
    target : []
})
var User = mongoose.model("User", userSchema);
//creat a documenent 

var user1 = new User({
    name : "jack",
    target :[{
        "10" : "true",
        "id" : "ePce6fBAHx9KeKjuM"
    }]
})
user1.save(user1, function(err, user){
    console.log(user)
})
User.findOneAndUpdate(
    {"name" : "jack"},
    {safe : true, upsert : true, new :true},
    function(err, model){
        model.target[0]["30"] = "true"
        console.log(model.target)
    }
)

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