node.js - Looping through Mongoose results returns undefined -


i have 2 mongodb collections , have defined schemas in mongoose. file.fileschema file name eg. "whatever.txt" , (filecatschema.path) 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 api have populated files file categories (filecatschema) , want return full path on request /api/files/ when try access properties inside populated json data gets returned undefined. can explain happening here? going through same process in different environment e.g. chrome's console gives me data want.

api.get('/files/', function(req, res) {   apimodel.files   .find({})   .populate('cat_id')   .exec(function(err, data) {     for(var i=0; < data.length; i++){       if(data[i].file){              console.log(data[i].cat_id)             /*this returns array data want:             [{"_id":"55d5e588dfd76d1dec880cd0",             "branch":"complete",             "name":"frequently accessed files",             "path":"complete/faf/","cat_id":[]             }] */                console.log(data[i].cat_id[0].path);             /*but returns undefined , have no idea why*/         }     }     if (err) res.send(err);     res.json(data);   }); }); 

i found answer! i'm not dealing regular object. looped through object's properties , discovered there many added mongoose, including 1 method "tojson". quick fix use this:

api.get('/files/', function(req, res) {   apimodel.files   .find({})   .populate('cat_id')   .exec(function(err, data) {     //add project category path api     for(var i=0; < 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: understand supposed ask in first place. lean() method returns stripped down result: lean json object. convert mongoose docs json


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -