gpt4 book ai didi

node.js - NodeJs - 如何从 Mongoose 输出中获取键值

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:50 25 4
gpt4 key购买 nike

我正在使用下面的函数来查询 Mongoose 模型,它的输出为

[{"count":10000}]。我想知道如何从 mongoose 返回的 json 中检索 count 的值,以便我可以使用它来执行某些算术运算。

 module.exports.getNext = function (field, model) {

mongoose.model(collection, identityCounterSchema).find({ 'field': field, 'model': model }, { "count": 1, "_id": 0 }, function (err, result) {
console.log(JSON.stringify(result))
var jsonObj = JSON.parse(JSON.stringify(result));
console.log(jsonObj.count)
return (jsonObj.count);
});
}

上述代码片段中的 jsonObj.count 返回未定义。

最佳答案

result 在数组中,需要使用 result[0].count 来获取计数。而且您不需要将 result 解析为字符串,然后再解析回对象,它已经是一个对象了。

此外,如果您只想获取一个文档,您应该使用 model.findOne() 函数:

mongoose.model(collection, identityCounterSchema)
.findOne({ field, model })
.then(obj => {
console.log(obj);
return (obj.count);
})
.catch(err => /* process error*/);

关于node.js - NodeJs - 如何从 Mongoose 输出中获取键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45392742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com