将数组中的元素推入,这是另一个对象在特定位置的键 [英] Push element in array which is the key of another object at specific position
问题描述
我有一个看起来像猫鼬的模型:
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": []
}]
}
我想在question.answers[1].comment
中添加评论,但我无法通过findOneAndUpdate
进行评论.
这是我尝试过的:
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) {...
但我收到此错误:MongoError: exception: The positional operator did not find the match needed from the query. Unexpanded update: answers.$.comments
.
推荐答案
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
}
)
如
如果您知道嵌入式文档的数组索引,则可以使用点符号.
这篇关于将数组中的元素推入,这是另一个对象在特定位置的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!MySchema.findOneAndUpdate(
{ "_id": questionId },
{ "$push": { "question.answers.1.comments": { "$each": [comment] } } },
function(err, doc) {
//Do something
}
)