简体   繁体   English

如何通过$ inc在猫鼬中增加价值

[英]How to increment value via $inc in Mongoose

I am trying to increment a field value using $inc without too much success. 我试图使用$inc增加字段值,但没有太大的成功。 I have the following schema: 我有以下架构:

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 }
});

I am trying to increment values in counter , and what I have is: 我试图增加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));
  ...

I was able to successfully increment in mongod using the statement, 我可以使用以下语句在mongod中成功递增,

db.posts.update({_id: ObjectId('56cd78fddfe1372131a04b4d')}, {$inc: {'counter.upvotes': 1}})

so I initially thought it had to do with Mongoose syntax, and tried number of variations including: 所以我最初认为它与Mongoose语法有关,并尝试了多种变体,包括:

  1. Using collection...update().exec(... ) format 使用collection...update().exec(... )格式
  2. Enclosing keys and values in single, double, no quote 将键和值括在单引号,双引号和无引号中
  3. Omitting ObjectId , ie, { '_id': id) } 省略ObjectId ,即{ '_id': id) }

But so far no luck. 但到目前为止还没有运气。 Any help would be greatly appreciated. 任何帮助将不胜感激。

PS. PS。 The code does execute successfully without error, and I get back a post since I set the option to {'new': true} . 代码确实成功执行,没有错误,并且由于将选项设置为{'new': true} ,所以我得到了回帖。 It's just that either of post.counter.[upvote | 只是post.counter中的任何一个。[upvote | downvote] is incremented in what's returned nor in the mongodb. [downvote]在返回的内容或mongodb中均递增。

Your where and update variables need to contain objects, not strings. 您的whereupdate变量需要包含对象,而不是字符串。

So it should be like this instead: 因此应该改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM