是否有什么我遗漏的东西可以让项目记录为带有参数的对象,但是当我尝试访问该参数时,它是未定义的?
到目前为止我已经尝试过:
console.log(item)
=>{ title: "foo", content: "bar"}
没关系console.log(typeof item)
=> objectconsole.log(item.title)
=> "未定义"
我将包含一些上下文,以防万一它与问题相关。
var TextController = function(myCollection) {
this.myCollection = myCollection
}
TextController.prototype.list = function(req, res, next) {
this.myCollection.find({}).exec(function(err, doc) {
var set = new Set([])
doc.forEach(function(item) {
console.log(item) // Here item shows the parameter
console.log(item.title) // "undefined"
set.add(item.title)
})
res.json(set.get());
})
}
根据建议,我在此行之前删除了 debugger
,以通过节点 repl 调试器检查实际是什么项目。这是我发现的:http://hastebin.com/qatireweni.sm
从这里我尝试了 console.log(item._doc.title)
并且效果很好。所以,现在这似乎更像是一个 Mongoose 问题。
有与此类似的问题,但它们似乎与对象的“this”访问有关,或者他们试图使对象超出函数的范围。在这种情况下,我不认为我在做任何一个,但如果我错了,请告诉我。谢谢
最佳答案
解决方案
您可以调用 toObject
方法来访问这些字段。例如:
var itemObject = item.toObject();
console.log(itemObject.title); // "foo"
为什么
正如您所指出的,真正的字段存储在文档的 _doc
字段中。
但是为什么 console.log(item)
=> { title: "foo", content: "bar"}
?
来自 the source code of mongoose(document.js) ,我们可以发现Document
的toString
方法调用了toObject
方法。因此 console.log
将“正确”显示字段。源码如下图:
var inspect = require('util').inspect;
...
/**
* Helper for console.log
*
* @api public
*/
Document.prototype.inspect = function(options) {
var isPOJO = options &&
utils.getFunctionName(options.constructor) === 'Object';
var opts;
if (isPOJO) {
opts = options;
} else if (this.schema.options.toObject) {
opts = clone(this.schema.options.toObject);
} else {
opts = {};
}
opts.minimize = false;
opts.retainKeyOrder = true;
return this.toObject(opts);
};
/**
* Helper for console.log
*
* @api public
* @method toString
*/
Document.prototype.toString = function() {
return inspect(this.inspect());
};
关于javascript - Mongoose/MongoDB 结果字段在 Javascript 中显示为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18710043/