2013-05-03 119 views
6

我正在处理一些与Mongoose查询,我需要跳过和限制子文档,但在同一个查询中,我想增加文档中的某个字段。目前我的查询是用链接构建的,因为当我试图用选项来完成时,我遇到了很多问题。这是我有:猫鼬 - 与findOne增量

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,但正如我所说的,我尝试了很多东西,它只是没有工作。

回答

14

您可以使用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); 
    } 
    }); 
+6

您的$ INC – Lion789 2016-02-29 17:47:08

+1

后失踪支架请注意:fieldToIncrement仍然没有变db_res – tuananh 2016-10-06 08:38:14

+1

对不起,小白,即将倒闭增加,但哪里$ INC从何而来?我不确定我理解那部分? – trainoasis 2017-03-18 17:58:59