danielgormly
danielgormly

Reputation: 1070

Looping through Mongoose results returns undefined

I have two mongodb collections and I have defined the schemas in Mongoose. Basically file.fileSchema is the file name eg. "whatever.txt" and (fileCatSchema.path) is the path eg. "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
});

In my API I have successfully populated files with file categories (fileCatSchema) and want to return the full path on request to /api/files/ but when I actually try to access the properties inside the populated json data it gets returned as undefined. can anyone explain what is happening here? going through the same process in a different environment e.g. chrome's console gives me the data I want.

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);
  });
});

Upvotes: 0

Views: 1498

Answers (1)

danielgormly
danielgormly

Reputation: 1070

I found my answer! I'm not dealing with a regular object. I looped through the object's properties and discovered there were many added by Mongoose, including one method "toJSON". My quick fix was to use this:

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);
  });
});

Update: Now I understand what I was supposed to ask in the first place. The lean() method returns a stripped down result: A lean JSON object. Convert Mongoose docs to json

Upvotes: 3

Related Questions