【问题标题】:How to increment value via $inc in Mongoose如何在 Mongoose 中通过 $inc 增加价值
【发布时间】: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 语法有关,并尝试了多种变体,包括:

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

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

附言。该代码确实成功执行而没有错误,并且由于我将选项设置为{'new': true},因此我回复了一个帖子。这只是 post.counter.[upvote | downvote] 在返回的内容和 mongodb 中都会增加。

【问题讨论】:

    标签: javascript json node.js mongodb


    【解决方案1】:

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

    所以它应该是这样的:

    let where = { '_id': ObjectId(req.body.pid) };
    let update = req.body.action === 'up' ? { '$inc': { 'counter.upvotes': 1 } }
                                          : { '$inc': { 'counter.downvotes': 1 } };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 2020-09-14
      • 1970-01-01
      • 2017-05-17
      • 2012-01-27
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多