Push element in array which is the key of another object at specific position

强颜欢笑 提交于 2019-12-11 20:14:15

问题


I have a mongoose model looking like that :

"question": {
    "_id": "1234",
    "title": "Hi",
    "content": "Hello",
    "viewed": 34425,
    "answers": [{
        "vote": 0,
        "date": "2015-12-21T13:03:14.334Z",
        "author": "john",
        "content": "hello",
        "comments": []
    }, {
        "vote": 0,
        "date": "2015-12-21T13:05:27.411Z",
        "author": "patrick",
        "content": "bonjour",
        "comments": []
    }]
}

I want to push a comment into question.answers[1].comment but I don't manage to do it with findOneAndUpdate.
Here is what i've attempted :

MySchema.findOneAndUpdate({_id: questionId}, 
    {$push: 
        {'answers.$.comments': {
              '$each': [comment], 
              '$position': 1}
        }
    }, function(err, doc) {...

but I get this error : MongoError: exception: The positional operator did not find the match needed from the query. Unexpanded update: answers.$.comments.


回答1:


The problem is that to use the positional $ update operator the array field must appear as part of the query document.

MySchema.findOneAndUpdate(
    { "_id": questionId, "question.answers.author": "patrick" }, 
    { "$push": { "question.answers.$.comments": { "$each": [comment] } } }, 
    function(err, doc) {
        //Do something
    }
)

As mentioned in the documentation:

If you know the array index of the embedded document, you can specify the document using the embedded document’s position using the dot notation.

MySchema.findOneAndUpdate(
    { "_id": questionId }, 
    { "$push": { "question.answers.1.comments": { "$each": [comment] } } }, 
    function(err, doc) {
        //Do something
    }
)


来源:https://stackoverflow.com/questions/34665550/push-element-in-array-which-is-the-key-of-another-object-at-specific-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!