javascript - Mongoose recursive query parent reference -


i trying mongo example doing in mongoose. seems more complex me in mongoose. possibly i'm trying fit square peg in round hole?

this example http://www.codeproject.com/articles/521713/storing-tree-like-hierarchy-structures-with-mongod (tree structure parent reference)

i'm trying build path.

var path=[]; var item = db.categoriespco.findone({_id:"nokia"}); while (item.parent !== null) {     item=db.categoriespco.findone({_id:item.parent});     path.push(item._id); } path.reverse().join(' / '); 

thanks!

mongoose asynchronous library,

db.categoriespco.findone({_id:"nokia"}); 

doesn't return answer query, returns query object itself. in order run query, you'll need either pass in callback function findone() or run exec() on query object returned.

db.categoriespco.findone({_id:"nokia"}, function (err, item) { }); 

however, can't use same while loop code generate path, you'll need use recursion instead. should work:

var path=[];  function addtopath(id, callback) {     db.categoriespco.findone({_id:id}, function (err, item) {       if (err) {           return callback(err);       }       path.push(item._id);       if (item.parent !== null) {           addtopath(item.parent, callback);       }       else {           callback();       }     }); }  addtopath("nokia", function (err) {   path.reverse().join(' / '); }); 

nb in addition, instead of pushing new items onto end of path array , reversing it, use path.unshift() adds item beginning of array.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -