【问题标题】:Mongoose $pushAll overwrites current array objectsMongoose $pushAll 覆盖当前数组对象
【发布时间】:2014-03-27 08:13:22
【问题描述】:

所以我有这个文档,我试图更新 cmets,当我这样做时,它似乎用新的信息覆盖了数组。知道为什么吗?

Confession.findOne({_id: confessionID}, function (err, confession) {
    if (err){
        console.log(err);
    } else {

           confession.update(
                {$pushAll: {'comments.commentData':
                    [{comment: req.body.text, commenter: req.body.name }]
                }},
                {upsert: true},
                function (err, confession) {
                    if (err) {
                        console.log(err);

                    } else {
                        res.send(confession.comments);
                        console.log(confession);
                    }
                });
            }

这是一个根据要求提供的示例文档

 { "__v" : 0,
   "_id" : ObjectId( "5171c2bd47a7510000000002" ),
   "absolves" : { "IDs" : [ null ],
   "num" : 2 },
   "comments" : { "commentData" : [
      { "comment" : "asdfas wdfwe cqwe qwe w w",
        "_id" : ObjectId( "5179c9fa79c165e74d000002" ),
        "timeStamp" : Date( 1366936058266 ) }],
   "num" : 0 },
   "condemns" : { "IDs" : [ null ],
   "num" : 2 },
   "facebook" : 1232876940,
   "removed" : false,
   "text" : " another confession",
   "time" : Date( 1366409917817 ) }

【问题讨论】:

  • 不是答案,但为什么upsert?您知道该文档存在,因为您刚刚通过 id 找到它。在这件事上,你可以跳过嵌套异步只需执行 Confession.update({_id: confessionID}, update, callback)
  • 您能否在更改之前或之后(或两者)包含示例文档?
  • 我在示例文档中进行了编辑,commentData 中的数组刚刚被新数据覆盖
  • 您可以发布您的架构或链接到我可以运行以重现的代码吗?我运气不好gist.github.com/aheckmann/5510698

标签: javascript node.js mongodb mongoose


【解决方案1】:

试试这个

{$push: {'comments.commentData':
                    {comment: req.body.text, commenter: req.body.name }
                }},

【讨论】:

    猜你喜欢
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2018-01-20
    • 2017-04-16
    • 2014-02-13
    • 2021-06-04
    • 2014-07-21
    相关资源
    最近更新 更多