mongoose findByIdAndUpdate只更新文档中的一个字段
我想增加upvotes当用户点击一些button,还存储他的stormpath用户ID(req.user.href)在一个数组中。
尝试1:
if (newUpvoters = found_post[0].upvoters.indexOf(req.user.href) == -1) { Problem.findByIdAndUpdate(found_post[0].id, { $push: { upvoters: req.user.href }} , {$inc: { upvotes : 1 } }, function (err, post) { if (err) return next(err); res.json(post); }) }
结果:只有upvoters数组被正确更新。 Upvotes不增加。
尝试2:
Problem.findByIdAndUpdate(found_post[0].id, {$inc: { upvotes : 1 } }, { $push: { upvoters: req.user.href }}, function (err, post) { if (err) return next(err); res.json(post); })
结果:只有Upvotes得到递增,upvoters数组没有更新。
尝试3:
Problem.findByIdAndUpdate(found_post[0].id, {$set : {$inc: { upvotes : 1 } , $push: { upvoters: req.user.href }} }, function (err, post) { if (err) return next(err); res.json(post); })
结果:没有发生
我想要做什么:更新Upvoters数组并将upvotes增加1。
您需要将$inc
和$push
操作符放到同一个对象中:
Problem.findByIdAndUpdate(found_post[0].id, { $inc: { upvotes : 1 }, $push: { upvoters: req.user.href } }, function (err, post) { if (err) return next(err); res.json(post); })
- 在node.js-mongodb中分组
- mongoose更新位置/指数数组中的项目
- 为什么在mongoose查询之前使用process.nextTick()?
- mongodb mongoose nodejs express4为什么自动在Object Array字段中插入一个_id?
- mongoose:更新不起作用
- 使用Node.js,Express.js和gridfs-stream直接将文件stream式传输到GridFS
- CastError:在尝试保存mongoose时投射undefined_method错误失败
- Heroku上的Node.js Express App不会使用Mongoose连接到MongoLab数据库
- Node.js $ http PUT请求不向服务器返回任何内容