猫鼬更新多个文档不会更新任何内容 [英] Mongoose update multiple documents doesn't update anything

查看:68
本文介绍了猫鼬更新多个文档不会更新任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签架构:

var labelSchema = mongoose.Schema({
   name: String,
   desc: String,
   postIds: [mongoose.Schema.ObjectId],
   removed: { type: Boolean, default: false }
})

当标签分配给帖子时,我想更新postIds数组,所以我在更新帖子请求中这样做:

I want to update postIds array when a label is assigned to a post, so I do in my update post request:

Label.update({'_id': { $in: post.labelIds }}, {$addToSet: {postIds:req.body.id}}, {multi: true})

其中post.labelIds是标签ID的数组.我已经用find()方法测试了查询,它工作正常,可以找到所有标签.但是,当我检查数据库中是否有更新的记录时,没有标签被更新.

Where post.labelIds is an array of label ids. I've tested the query with find() method and it works fine, it finds all the labels. However when I check the database for updated records, no label is updated.

当我在update命令之前执行post.LabelIds的console.log时,它返回:

When I do a console.log of post.LabelIds before the update command, it returns:

[ 'uniqueidhere', 'anotheruniqidthere' ]

和req.body.id

and req.body.id

uniqueidhere

因此ID在那里,但是以某种方式无法进行更新.

So the ids are there, but somehow the update doesn't work.

推荐答案

花了几个小时试图找出错误的出处以及为什么它没有更新数据库后,我才发现它实际上确实在更新数据库.问题是我正在检查mongo shell中的更新,并且在通过nodejs post请求更新它之后,它没有作为更新出现在shell中.但是,当我console.log()标签时,它已更新.因此,我进一步调查了该问题,发现问题不是mongo shell,而是使用不正确的mongoose命令更新.我缺少回调参数.添加回调函数后,数据立即在mongo shell中更新.

After a few hours spend trying to find out where the error was and why it wasn't updating the database, I found out it actually did update the database. The problem was that I was checking the update in mongo shell and after I updated it over nodejs post request, it didn't appear in the shell as updated. However when I console.log() the labels, it was updated. So I investigated the problem further and I found out that the the problem wasn't the mongo shell, but incorrect usage of mongoose command update. I was missing the callback argument. After adding the callback function, the data were updated in the mongo shell immediately.

所以不要这样做:

Label.update({'_id': { $in: post.labelIds }}, {$addToSet: {postIds:req.body.id}}, {multi: true})

一定不要忘记添加回调:

It mustn't be forgotten to add callback:

Label.update({'_id': { $in: post.labelIds }}, {$addToSet: {postIds:req.body.id}}, {multi: true}, function(err, affected) {
   if(err)
      console.log(err)
   else
      console.log(affected)
      // After successful update, redirect here to another page...

或者作为重复的答案建议运行exec():

Or as duplicate answer suggests running exec():

Label.update({'_id': { $in: post.labelIds }}, {$addToSet: {postIds:req.body.id}}, {multi: true}).exec()

这篇关于猫鼬更新多个文档不会更新任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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