1
votes

Let's say i have 5 documents in members collection as follow:

[
  {
    _id: ObjectId("60e6afadfb6fe6510155e9b2"),
    name: "James",
    parentId: ObjectId("60e6afadfb6fe6510155e9b1")
  },
  {
    _id: ObjectId("60e6afadfb6fe6510155e9b1"),
    name: "Michael",
    parentId: ObjectId("60e6afadfb6fe6510155e9b0")
  },
  {
    _id: ObjectId("60e6afadfb6fe6510155e9b0"),
    name: "Josh",
    parentId: ObjectId("60e6afadfb6fe6510155e9af")
  },
  {
    _id: ObjectId("60e6afadfb6fe6510155e9af"),
    name: "Robert",
    parentId: ObjectId("60e6afadfb6fe6510155e9ad")
  },
  {
    _id: ObjectId("60e6afadfb6fe6510155e9ad"),
    name: "William",
    parentId: null
  },
  
]

All I want is to iterate through those documents to get the full name of James
My output should look like 'James Michael Josh Robert William' consider that the parentId in the child document is the _id of the parent document

1

1 Answers

0
votes

You can use the concept of the linked list to traverse through an array. To my knowledge, it is not possible on the DB level, and since you have mentioned the nodejs tag. So here is a nodejs solution

const {Types: {ObjectId}} = require("mongoose")

let data = [
  {
    _id: ObjectId("60e6afadfb6fe6510155e9b2"),
    name: "James",
    parentId: ObjectId("60e6afadfb6fe6510155e9b1")
  },
  {
    _id: ObjectId("60e6afadfb6fe6510155e9b1"),
    name: "Michael",
    parentId: ObjectId("60e6afadfb6fe6510155e9b0")
  },
  {
    _id: ObjectId("60e6afadfb6fe6510155e9b0"),
    name: "Josh",
    parentId: ObjectId("60e6afadfb6fe6510155e9af")
  },
  {
    _id: ObjectId("60e6afadfb6fe6510155e9af"),
    name: "Robert",
    parentId: ObjectId("60e6afadfb6fe6510155e9ad")
  },
  {
    _id: ObjectId("60e6afadfb6fe6510155e9ad"),
    name: "William",
    parentId: null
  },
]

let names = []
let current = data[0]

// handle null / undefined current value
while(current) {
    names.push(current.name)
    current = data.find(v=>v._id.equals(current.parentId))
}

console.log(names.join(' ')) // James Michael Josh Robert William