简体   繁体   English

mongoDB:在(嵌套)对象中添加和更新某些字段

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

This is a mongoDB document, to which I need to add some data: 这是一个mongoDB文档,我需要向其中添加一些数据:

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

I need to update existing fields in target or add them, if they do not exist. 我需要更新target现有字段或添加它们(如果它们不存在)。 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: 但是用10代替了30 ,但是我希望得到这样的结果:

{
    "_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. 数组是您的target字段,因此请确保类型是架构中的数组。 To update the array select the array by the id or field of your choice. 要更新阵列,请根据您选择的ID或字段选择阵列。

This code finds the field and adds the "30" : "true", and leaves the other information in the object inside an array. 这段代码找到该字段并添加"30" : "true",并将其他信息保留在数组内的对象中。 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)
    }
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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