【问题标题】:Looping through Mongoose results returns undefined循环遍历 Mongoose 结果返回未定义
【发布时间】:2015-11-25 00:09:47
【问题描述】:

我有两个 mongodb 集合,并且我在 Mongoose 中定义了模式。基本上 file.fileSchema 是文件名,例如。 “whatever.txt”和(fileCatSchema.path)是路径,例如。 "c:/text/"。

var fileSchema = new Schema({
  name : String,
  file : String,
  cat_id : [{ type: ObjectId, ref: 'fileCategories' }]
});

var fileCatSchema = new Schema({
  branch : String,
  file : String,
  path : String
});

在我的 API 中,我已经成功地使用文件类别 (fileCatSchema) 填充了文件,并希望根据请求将完整路径返回到 /api/files/,但是当我实际尝试访问填充的 json 数据中的属性时,它会返回为不明确的。谁能解释这里发生了什么?在不同的环境中经历相同的过程,例如chrome 的控制台给了我我想要的数据。

api.get('/files/', function(req, res) {
  apiModel.files
  .find({})
  .populate('cat_id')
  .exec(function(err, data) {
    for(var i=0; i < data.length; i++){
      if(data[i].file){

            console.log(data[i].cat_id)
            /*This returns the array with the data i want:
            [{"_id":"55d5e588dfd76d1dec880cd0",
            "branch":"complete",
            "name":"Frequently Accessed Files",
            "path":"complete/faf/","cat_id":[]
            }] */



            console.log(data[i].cat_id[0].path);
            /*But this returns undefined and I have no idea why*/


      }
    }
    if (err) res.send(err);
    res.json(data);
  });
});

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    我找到了答案!我不是在处理常规对象。我遍历了对象的属性,发现 Mongoose 添加了许多属性,包括一种方法“toJSON”。我的快速解决方法是使用这个:

    api.get('/files/', function(req, res) {
      apiModel.files
      .find({})
      .populate('cat_id')
      .exec(function(err, data) {
        //Add Project category path to API
        for(var i=0; i < data.length; i++){
          if(data[i].file){
            var fullPath = data[i].cat_id[0].toJSON().path + data[i].file;
            data[i].file = fullPath;
        }
      }
        if (err) res.send(err);
        res.json(data);
      });
    });
    

    更新:现在我明白了我应该首先问什么。 lea() 方法返回一个精简的结果:一个精简的 JSON 对象。 Convert Mongoose docs to json

    【讨论】:

      猜你喜欢
      • 2013-02-19
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 2019-02-18
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      相关资源
      最近更新 更多