鍍金池/ 問答/數(shù)據(jù)庫(kù)  HTML/ 【mongoose】save方法報(bào)錯(cuò)

【mongoose】save方法報(bào)錯(cuò)

數(shù)據(jù)如下:
{
    array: [
        {
            _id: 'aaa'
            sub_array: [
                {
                    _id: 'saaa',
                    name: 'aaa'
                },
                {...}
            ]
        },
        {...}
    ]
}

現(xiàn)在我要更新sub_arrayname值:

Model.findOne({
    'array._id': 'aaa'
},{'array.$': 1}).then(respon=> {
    let checkdt = respon.array[0].sub_array.find((item)=> {
        reruen item._id == 'saaa'
    })
    checkdt.name = 'new val'
    respon.save().then(r=> res.send(r)).catch(er=> res.send(er))
})

結(jié)果報(bào)錯(cuò):

{
    "message": "For your own good, using `document.save()` to update an array which was selected using an $elemMatch projection OR populated using skip, limit, query conditions, or exclusion of the _id field when the operation results in a $pop or $set of the entire array is not supported. The following path(s) would have been modified unsafely:\n  questions.0.sub_questions.1.score\n  questions.0.sub_questions.1.title\nUse Model.update() to update these arrays instead.",
    "name": "DivergentArrayError"
}

為什么會(huì)這樣?我該怎么修改?

回答
編輯回答
淺時(shí)光

你用的是mongoose?

2017年2月22日 07:48
編輯回答
忘了我

搜一下其實(shí)有人問過的:https://stackoverflow.com/que...
mongoose的github上也對(duì)這個(gè)問題有描述:issues#1334
簡(jiǎn)單地說,你用findOne的時(shí)候用了投影{'array.$': 1},所以返回的文檔中只有原始文檔的一部分。而save方法是把你給的文檔原樣存回去,這顯然不是你想要的結(jié)果,因?yàn)闀?huì)丟數(shù)據(jù)。舉例:

rs0:PRIMARY> db.test.insert({a: 1, b: 2})
WriteResult({ "nInserted" : 1 })
rs0:PRIMARY> db.test.find()
{ "_id" : ObjectId("5a741072979a928dbe90341a"), "a" : 1, "b" : 2 }
rs0:PRIMARY> var doc = db.test.findOne({}, {a: 1})
rs0:PRIMARY> db.test.save(doc)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
rs0:PRIMARY> db.test.find()
{ "_id" : ObjectId("5a741072979a928dbe90341a"), "a" : 1 }

說白了,mongoose是在防止你自殘,還是挺有節(jié)操的,業(yè)界良心。

2017年7月26日 04:53