【问题标题】:Push element in array which is the key of another object at specific position推入数组中的元素,该元素是特定位置另一个对象的键
【发布时间】:2016-04-12 10:58:33
【问题描述】:

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

"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 做到这一点。
这是我尝试过的:

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

【问题讨论】:

  • 我刚刚编辑了问题,添加了错误。

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

问题在于,要使用位置 $ 更新运算符,数组字段必须作为查询文档的一部分出现。

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

documentation中提到的:

如果您知道嵌入文档的数组索引,则可以使用 dot notation 使用嵌入文档的位置指定文档。

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

【讨论】:

    猜你喜欢
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2013-03-25
    相关资源
    最近更新 更多