首页 > 解决方案 > 当我尝试访问我查询的文档元素时,Mongoose 返回 undefined

问题描述

上下文:我试图简单地控制台记录我查询的文档中的值。我成功地找到了文件。我知道是因为我在打印出我正在寻找的文档的价值之前打印出文档。文档打印查找,另一方面,该字段显示为未定义。

这是代码:

架构:

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.

我已确保架构与正确的集合相关。我尝试打印返回对象的文档类型。

标签: javascriptdatabasemongodbmongoose

解决方案


推荐阅读