Thursday, 11 May 2017

How do I find the recursive path to an object reference in mongodb/mongoose?

I have a mongoose model with parent references:

const GroupSchema = new Schema({
  name: {
    type: String,
    required: true,
    unique: true
  },
  parent: {
    type: Schema.Types.ObjectId,
    ref: 'group'
  }});

I would like to get the path to an object by traveling up the parent references and adding them to an array.

I've tried doing this a few ways, but I'm stuck here:

  const groupId = req.params.id;
  const path = [];

  function addToPath(id){
    Group.findById(id)
      .then(results => {
        if(results.parent !== null){
          path.unshift({ _id: results._id, name: results.name });
          addToPath(results.parent);
        } else {
          return res.send(path);
        }
      })
      .catch(next);
    }

    addToPath(groupId);

I can't seem to get results into the array. What is the best way to do this? Am I moving in the right direction?



via khndrx

No comments:

Post a Comment