我看到很多使用collection.findOne({query}).field
的教程/指南来获取返回的文档中的字段值,但对我来说似乎不起作用,我想知道为什么。我确实找到了另一种方法来做到这一点。见下文:
var rank = function(id) {
// My way of doing it
collection.findOne({ _id: id }, function(err, doc) {
console.log(doc.score); // Prints the actual score
});
// How some tutorials do it
var score = collection.findOne({ _id: id }).score;
console.log(score); // Gives a TypeError (Cannot read property 'score' of undefined)
};
答案 0 :(得分:8)
//一些教程如何做到
这些教程可能使用mongodb的shell,而不是node.js api。 shell的api看起来很相似(所有相同的单词,findOne
等),但它没有使用回调。 Shell的findOne
确实以内联方式返回文档。