我看到很多教程/指南使用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)
};
发布于 2017-08-14 05:11:11
//有些教程是如何做到的
这些教程可能使用的是mongodb的shell,而不是node.js api。shell的api看起来类似(所有相同的单词、findOne
等),但它不使用回调。Shell的findOne
确实会内联地返回文档。
https://stackoverflow.com/questions/45675236
复制相似问题