NodeJs – 如何从mongoose输出获取关键值

我正在使用下面的函数来查询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返回undefined。

result一个数组,你需要使用result[0].count来计数。 而且你不需要parsingresult的string,然后回到对象,它已经是一个对象。

另外,如果你只想得到一个文档,你应该使用model.findOne()函数:

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