mongoose 给文档的子数组的头部插入数据

mongoose 中可使用 $push 向子文档数组末尾添加数据,但如果想在数组头部添加数据,好像没有$unshift 方法。但可以利用$each、$postition把数据插入到指定的数组位置。

下面的代码片段是把 comment 插入到 comments 的头部,而不是默认的末尾,即指定 position 为 0: 

articleModel.update({
                _id: articleId
            }, {
                '$push': {
                    comments:{ $each:[comment],$position: 0}
                }
            }, function (err, docs) {
                if (err) return next(err);
                res.json(docs);

            })

猜你喜欢

转载自www.cnblogs.com/anyjs/p/12516758.html