node.js - 无法使用 mongoose 在 mongodb 中增加字段
问题描述
我在 mongodb 中有一个文档。此函数中的文档能够找到该文档并将其返回,但我无法终生使用此函数将计数字段更新 1。如果有帮助,mongodb 中的当前文档是:
{
_id: 60c5e4c3fba7edd232cf57e7,
counterName: 'give_me_the_count',
count: 1,
updatedAt: 2021-06-13T11:47:02.575Z
}
该代码将原始文档返回给 updatedCounter。但是 updatedCounter.count 是未定义的。
async function updateAndReturnNewCount() {
let doc = await Counter.findOne({ counterName : "give_me_the_count" })
var count = doc.count
let updatedCounter = await Counter.findOneAndUpdate({ counterName : "give_me_the_count" },
{ $inc: {"count" : 1 }},
{ new: true,
useFindAndModify: false },
function(err, doc) {
if (err) { console.log(err)}
else {console.log("success")}
}
);
console.log("updateAndReturnNewCount fired")
return updatedCounter.count
}
解决方案
您的查询对于您想要执行的操作不正确。
试试这个:
await Counter.aggregate([
{
$match: {
counterName : "give_me_the_count"
}
},
{
$set: {
"count": {
$add: [ "$count", 1 ] // Increment $count by one
}
}
}
])
编辑:
用法:
async function updateAndReturnNewCount() {
let doc = await Counter.findOne({ counterName : "give_me_the_count" })
var count = doc.count
let updatedCounter = await Counter.aggregate([
{
$match: {
counterName : "give_me_the_count"
}
},
{
$set: {
"count": {
$add: [ "$count", 1 ] // Increment $count by one
}
}
}
])
console.log("updateAndReturnNewCount fired");
console.log(updatedCounter);
return count++;
}
推荐阅读
- windows - 禁用切换到 windows 和 mac 上的不同应用程序
- consul - 如何设置单节点 Consul 服务器/客户端?
- azure-devops - 源链接无法从私有 azure 符号服务器下载 nuget 的源文件,使用了错误的域 dev.azure.com/raw/
- c# - 使用 C# Azure Datalake Gen1 客户端的间歇性错误“底层连接已关闭”
- opencv - 在 Linux 上将 OpenCL 与英特尔超高清显卡一起使用
- javascript - Firebase 实时数据库 - 订阅 .on() 不会在客户端触发
- django - 在将 python2 项目移植到 python3 时,mobileesp 的中间件出现错误
- jmeter - 内部服务器错误 - http://localhost:1080/webTours/home.html
- java-9 - jdk9 maven编译错误:模块从A和B读取包
- sql - SQL 查询根据该范围的行之前和之后的记录转换记录集或范围