猫鼬-使用findOne递增 [英] Mongoose - Increment with findOne
本文介绍了猫鼬-使用findOne递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用Mongoose处理一些查询,我需要跳过和限制子文档,但是在同一查询中,我想增加文档中的某些字段.目前,我的查询是使用链接建立的,因为尝试仅使用选项时会遇到很多问题.这就是我所拥有的:
I'm working on some query with Mongoose where I need to skip and limit subdocuments, but in the same query I want to increment some field in document. Currently is my query built with chaining, because I got a lot of problem when I tried to do it just with options. This is what I have:
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,但正如我所说,我尝试了很多事情,但它根本没有用.
I would like to increment filed 'views' for 1 when calling this query, but as I said, I tried a lot of things and it just didn't work.
推荐答案
您可以使用 findOneAndUpdate
修改文档,同时也要获取文档.
You can use findOneAndUpdate
to modify a document while also fetching one.
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);
}
});
这篇关于猫鼬-使用findOne递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文