将数组中的元素推入,这是另一个对象在特定位置的键 [英] Push element in array which is the key of another object at specific position

查看:72
本文介绍了将数组中的元素推入,这是另一个对象在特定位置的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像猫鼬的模型:

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
    }
)

如果您知道嵌入式文档的数组索引,则可以使用点符号.

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

这篇关于将数组中的元素推入,这是另一个对象在特定位置的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆