[英]Mongoose increment value not working
I am trying to increment a value and assign it back to the key. 我试图增加一个值并将其分配回键。
const TopicSchema = mongoose.Schema({
count: Number
});
topic.count += 2
Instead of 4, 22
returned. 而不是4,返回了
22
。 If I do it a couple of times, it is always appending 2 to the end like 2222
. 如果我做几次,它总是像末尾
2222
一样在末尾附加2。
What's wrong? 怎么了?
Sounds like you are concatenating strings instead of adding numbers. 听起来您是在连接字符串而不是添加数字。 Try wrapping
topic.count
in Number( )
尝试将
topic.count
包装在Number( )
If you'are trying to update the document you better use $inc
operator provided by mongodb
. 如果要更新文档,最好使用
mongodb
提供的$inc
运算符。 Read more about it here . 在此处了解更多信息。
By the way, this is how you can get it done in a single query 顺便说一下,这就是您如何在单个查询中完成它的方法
db.topic.update(
{ }, //your filter here
{ $inc: { count: 2} }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.