mongodb 使用 $inc 增加 Mongoose 的文档属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8621948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using $inc to increment a document property with Mongoose
提问by Randomblue
I would like to increment the views
count by 1 each time my document is accessed. So far, my code is:
views
每次访问我的文档时,我想将计数增加 1。到目前为止,我的代码是:
Document
.find({})
.sort('date', -1)
.limit(limit)
.exec();
Where does $inc
fit in here?
这里$inc
适合放哪里?
回答by Tyler Brock
Never used mongoose but quickly looking over the docs hereit seems like this will work for you:
从未使用过猫鼬,但快速查看此处的文档似乎对您有用:
# create query conditions and update variables
var conditions = { },
update = { $inc: { views: 1 }};
# update documents matching condition
Model.update(conditions, update).limit(limit).sort('date', -1).exec();
Cheers and good luck!
干杯,祝你好运!
回答by peerbolte
I ran into another problem, which is kind of related to $inc.. So I'll post it here as it might help somebody else. I have the following code:
我遇到了另一个问题,它与 $inc 有点相关。所以我会在这里发布它,因为它可能会帮助其他人。我有以下代码:
var Schema = require('models/schema.js');
var exports = module.exports = {};
exports.increase = function(id, key, amount, callback){
Schema.findByIdAndUpdate(id, { $inc: { key: amount }}, function(err, data){
//error handling
}
}
from a different module I would call something like
从不同的模块我会调用类似的东西
var saver = require('./saver.js');
saver.increase('555f49f1f9e81ecaf14f4748', 'counter', 1, function(err,data){
//error handling
}
However, this would not increase the desired counter. Apparently it is not allowed to directly pass the key into the update object. This has something to do with the syntax for string literals in object field names. The solution was to define the update object like this:
但是,这不会增加所需的计数器。显然不允许直接将密钥传递给更新对象。这与对象字段名称中字符串文字的语法有关。解决方案是像这样定义更新对象:
exports.increase = function(id, key, amount, callback){
var update = {};
update['$inc'] = {};
update['$inc'][key] = amount;
Schema.findByIdAndUpdate(id, update, function(err, data){
//error handling
}
}
回答by Ahmed_4EGA
Works for me (mongoose 5.7)
对我有用(猫鼬 5.7)
blogRouter.put("/:id", async (request, response) => {
try {
const updatedBlog = await Blog.findByIdAndUpdate(
request.params.id,
{
$inc: { likes: 1 }
},
{ new: true } //to return the new document
);
response.json(updatedBlog);
} catch (error) {
response.status(400).end();
}
});