user2301824
user2301824

Reputation: 11

Mongoose recursive query parent reference

I am trying to do exactly what this mongo example is doing but in mongoose. It seems more complex to me in mongoose. Possibly i'm trying to fit a square peg in a round hole?

This example is from http://www.codeproject.com/Articles/521713/Storing-Tree-like-Hierarchy-Structures-With-MongoD (tree structure with parent reference)

I'm trying to build a 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!

Upvotes: 1

Views: 2751

Answers (1)

matthewtole
matthewtole

Reputation: 3247

Mongoose is an asynchronous library, so

db.categoriesPCO.findOne({_id:"Nokia"});

doesn't return the answer to the query, it just returns a Query object itself. In order to actually run the query, you'll need to either pass in a callback function to findOne() or run exec() on the Query object returned.

db.categoriesPCO.findOne({_id:"Nokia"}, function (err, item) {
});

However, you can't use the same while loop code to generate the path, so you'll need to use recursion instead. Something like this 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 the end of the path array and then reversing it, you could use path.unshift() which adds the item to the beginning of the array.

Upvotes: 1

Related Questions