猫鼬 - 使用findOne增加

use*_*255 10 mongoose node.js

我正在使用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); } });
Run Code Online (Sandbox Code Playgroud)

我想在调用此查询时增加1的"视图",但正如我所说,我尝试了很多东西,但它没有用.

小智 19

您可以使用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); 
    } 
  });
Run Code Online (Sandbox Code Playgroud)

  • $ inc后你缺少一个方括号 (6认同)