javascript - 如何通过 Mongoose 中的 $inc 增加值(value)

标签 javascript json node.js mongodb

我尝试使用 $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 语法有关,并尝试了多种变体,包括:

  1. 使用collection...update().exec(...) 格式
  2. 将键和值括在单引号、双引号、无引号中
  3. 省略ObjectId,即{ '_id': id) }

但到目前为止还没有运气。任何帮助将不胜感激。

PS。该代码确实成功执行,没有错误,并且由于我将选项设置为 {'new': true},所以我收到了一条帖子。只是 post.counter.[upvote | 中的任何一个downvote] 在返回的内容和 mongodb 中都会递增。

最佳答案

您的 whereupdate 变量需要包含对象,而不是字符串。

所以应该是这样的:

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/

相关文章:

javascript - 编写 JSON 解析器以格式化饼图 (HighCharts) 的数据

node.js - 重定向到登录时出现 Keycloak CORS 问题

html - 带大括号的 Jade 环

javascript - 拖放项目并在数据库中更新后,如何在 jQuery Nestable 插件中获取子项和 ID?

javascript - 错误: bad URI when sending data as JSON with GET method to a Rails resource

javascript - 在 flex 容器中设置子div的宽度

python - 在运行 Yosemite 的 Mac 上完成 PyMySQL 的安装

javascript - JavaScript 中的管道 createElement 和appendChild

php - utf8_unicode_ci 似乎不是UTF8

node.js - MongoDB 聚合 - $lookup 性能