问题
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