【发布时间】:2016-02-26 04:30:46
【问题描述】:
我正在尝试使用$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 }
});
我正在尝试增加 counter 中的值,而我所拥有的是:
...
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) }
但到目前为止还没有运气。任何帮助将不胜感激。
附言。该代码确实成功执行而没有错误,并且由于我将选项设置为{'new': true},因此我回复了一个帖子。这只是 post.counter.[upvote | downvote] 在返回的内容和 mongodb 中都会增加。
【问题讨论】:
标签: javascript json node.js mongodb