Javascript 当我尝试访问我查询的文档的元素时,Mongoose返回undefined
上下文:我试图简单地控制台记录我查询的文档中的值。我正在成功地找到文件。我知道,因为我先打印文档,然后再打印我要查找的文档的值。文档打印find,另一方面字段显示为未定义 代码如下: 模式:Javascript 当我尝试访问我查询的文档的元素时,Mongoose返回undefined,javascript,database,mongodb,mongoose,Javascript,Database,Mongodb,Mongoose,上下文:我试图简单地控制台记录我查询的文档中的值。我正在成功地找到文件。我知道,因为我先打印文档,然后再打印我要查找的文档的值。文档打印find,另一方面字段显示为未定义 代码如下: 模式: const mongoose = require('mongoose'); const Schema = mongoose.Schema; let TextSchema = new Schema({ text_ID: {type: Number, required: true}, titl
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let TextSchema = new Schema({
text_ID: {type: Number, required: true},
title: {type: String, required: true, max: 100},
body: {type: String, required: true},
});
// Export the model
module.exports = mongoose.model('texts', TextSchema);
我知道Mongo为所有东西都创建了自己的ID,但现在请容忍我使用自己的ID。
下面是有问题的代码:
textModel.find({text_ID: currentTextLocation}, function(err, doc){
if(err){
console.log('error: ' + err);
}
console.log(doc);
console.log(doc.body);
currentTextBody = doc.body;
});
这是它给我的输出:
Database connection established!
[
{
_id: 5dc2915f1c9d440000ed7077,
text_ID: 1,
title: 'Kevin Abstract',
body: 'Kevin Abstract was a famous american rap artist.'
}
]
undefined
最后,它应该是这样的:
Database connection established!
[
{
_id: 5dc2915f1c9d440000ed7077,
text_ID: 1,
title: 'Kevin Abstract',
body: 'Kevin Abstract was a famous american rap artist.'
}
]
Kevin Abstract was a famous american rap artist.
我已确保模式与正确的集合相关。我尝试打印文档类型,它返回了一个对象。来自文档的o/p,它看起来是一个数组(如果超过1,则为文档数组)。尝试以
doc[0][“body”]
的身份访问body,希望我能给你一个绿色的小标志,因为这样做有效。我真的不明白它为什么起作用,但我很高兴它真的起作用了。从单据的o/p来看,它看起来是一个数组(如果超过1,则是一个文档数组)。尝试以doc[0][“body”]
的身份访问body,希望我能给你一个绿色的小标志,因为这样做有效。我真的不明白它为什么起作用,但我很高兴它起了作用。