2017-07-29 63 views
1

我使用下面的查詢功能,貓鼬模型得到的鍵值,並讓輸出的NodeJS - 如何從貓鼬輸出

[{「計數」:10000}]我想知道如何我從貓鼬返回的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。

+0

我什麼也看不到你的代碼錯誤,但'stringify'然後'parse'是多餘的?你可以使用結果作爲普通的JS對象! – thelonglqd

回答

1

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*/);