如果嵌套的对象键与数据库中的数据匹配,如何只推送更新某些字段?

时间:2019-01-14 09:54:02

标签: arrays mongodb mongodb-query

下面是我的数据的结构:

(stored in the database already)
{
    "_id" : ObjectId("5c3b917eff444cbc400a9939"),
    "data" : [ 
        {
            "role" : [ 
                "CARRY", 
                "CARRY", 
                "CARRY"
            ],
            "kills" : [ 
                "12", 
                "9", 
                "6"
            ],
            "_id" : ObjectId("5c3b917eff444cbc400a9955"),
            "name" : "Lisa",
            "rank" : "DIAMOND",
            "id" : 429,
            "count" : 3
},
{
    "_id" : ObjectId("5c3b917eff444cbc40042339"),
    "data" : [ 
        {
            "role" : [ 
                "CARRY", 
                "CARRY", 
                "CARRY"
            ],
            "kills" : [ 
                "5", 
                "2", 
                "1"
            ],
            "_id" : ObjectId("5c3b917eff444cbc400a9955"),
            "name" : "Joe",
            "rank" : "DIAMOND",
            "id" : 12,
            "count" : 3
},
...

现在让我们说有更多数据要更新,一个是丽莎的信息,另一个是新人的信息:

(new data that I have)
{
    "_id" : ObjectId("5c3b917eff444cbc400a9939"),
    "data" : [ 
        {
            "role" : [ 
                "SUPPORT", 
                "SUPPORT", 
                "SUPPORT"
            ],
            "kills" : [ 
                "0", 
                "1", 
                "3"
            ],
            "_id" : ObjectId("5c3b917eff444cbc400a9955"),
            "name" : "Lisa",
            "rank" : "DIAMOND",
            "id" : 429,
            "count" : 3
},
{
    "_id" : ObjectId("5c3b917eff444cbc40042339"),
    "data" : [ 
        {
            "role" : [ 
                "CARRY", 
                "CARRY", 
                "CARRY"
            ],
            "kills" : [ 
                "1", 
                "7", 
                "5"
            ],
            "_id" : ObjectId("5c3b917eff444cbc400a9955"),
            "name" : "James",
            "rank" : "DIAMOND",
            "id" : 32,
            "count" : 3
}

我只想将Lisa的新角色并杀死数组作为现有Lisa的角色并杀死数组,然后为James插入新唱片。

我尝试执行以下操作,其中data.data包含James的记录和Lisa的新信息。 (2个对象数组),因此我正在做一个for循环。

            for(let i=0;i<data.data.length;i++){
              ChampionData.findOne({"data.id":data.data[i].id},{"data.$":1},function(err,res){
               if(!res){
                 console.log('no match!')
               }else if(res.length!==0){
                 console.log('match found:')
                 console.log(res.data)
               }
             })
            }

任何帮助将不胜感激!

0 个答案:

没有答案