【问题标题】:Mongoose - Increment with findOneMongoose - 使用 findOne 递增
【发布时间】:2013-05-03 18:55:51
【问题描述】:

我正在使用 Mongoose 进行一些查询,我需要跳过和限制子文档,但在同一个查询中,我想增加文档中的某些字段。目前我的查询是使用链接构建的,因为当我尝试仅使用选项时遇到了很多问题。这就是我所拥有的:

Model.findOne({ shorten_id: id }).select('title content comments views').slice('comments', [0, 10]).exec(function(err, db_res) { if (err) { throw err; } else { console.log(db_res); } });

我想在调用此查询时将归档的“视图”增加 1,但正如我所说,我尝试了很多东西,但都没有奏效。

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您可以使用findOneAndUpdate 修改文档,同时获取一个文档。

    Model.findOneAndUpdate({ shorten_id: id }, { $inc: { fieldToIncrement: 1 })
      .select('title content comments views')
      .slice('comments', [0, 10])
      .exec(function(err, db_res) { 
        if (err) { 
          throw err; 
        } 
        else { 
          console.log(db_res); 
        } 
      });
    

    【讨论】:

    • $inc 后面少了一个括号
    • 请注意:变量 db_res 中的 fieldToIncrement 仍然没有增加
    • 抱歉这个菜鸟,但是 $inc 是从哪里来的?我不确定我是否理解那部分?
    • @trainoasis $inc 是 MongoDB 更新操作符,请参阅文档:docs.mongodb.com/manual/reference/operator/update/inc
    猜你喜欢
    • 2021-12-04
    • 1970-01-01
    • 2015-08-07
    • 2015-10-26
    • 2017-11-16
    • 1970-01-01
    • 2013-09-23
    • 2017-12-08
    • 2016-01-29
    相关资源
    最近更新 更多