我尝试使用 $inc
增加字段值,但没有取得太大成功。我有以下架构:
var postSchema = mongoose.Schema({
title : { type: String, required: true },
body : { type: String, default: '' },
counter : counterSchema
});
var counterSchema = mongoose.Schema({
upvotes : { type: Number, default: 0, min: 0 },
downvotes : { type: Number, default: 0, min: 0 },
view : { type: Number, default: 0, min: 0 }
});
我正在尝试增加计数器
中的值,我所拥有的是:
...
let where = `{ '_id': ObjectId("${req.body.pid}") }`:
let update = req.body.action === 'up' ? "{ '$inc': { 'counter.upvotes': 1 } }"
: "{ '$inc': { 'counter.downvotes': 1 } }";
Post.findOneAndUpdate(where, update, {'new': true}, (err, post) => {
if (err) return next(err);
console.log('post=' + JSON.stringify(post));
...
我能够使用该语句成功地增加 mongod,
db.posts.update({_id: ObjectId('56cd78fddfe1372131a04b4d')}, {$inc: {'counter.upvotes': 1}})
所以我最初认为这与 Mongoose 语法有关,并尝试了多种变体,包括:
- 使用
collection...update().exec(...
) 格式 - 将键和值括在单引号、双引号、无引号中
- 省略
ObjectId
,即{ '_id': id) }
但到目前为止还没有运气。任何帮助将不胜感激。
PS。该代码确实成功执行,没有错误,并且由于我将选项设置为{'new': true}
,所以我收到了一条帖子。只是 post.counter.[upvote | 中的任何一个downvote] 在返回的内容和 mongodb 中都会递增。
最佳答案
您的 where
和 update
变量需要包含对象,而不是字符串。
所以应该是这样的:
let where = { '_id': ObjectId(req.body.pid) };
let update = req.body.action === 'up' ? { '$inc': { 'counter.upvotes': 1 } }
: { '$inc': { 'counter.downvotes': 1 } };
关于javascript - 如何通过 Mongoose 中的 $inc 增加值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35643512/