How I can find data by id of folder and response folder and children

Viewed 26

My json data in mongoDB, example:

  {
    "_id": 1,
    "name": "ABC",
    "parentID": null
  },
  {
    "_id": 2,
    "name": "ABC.txt",
    "parentID": 1
  },
  {
    "_id": 3,
    "name": "ABCD",
    "parentID": 1
  },
  {
    "_id": 4,
    "name": "ABC 3",
    "parentID": 3
  },
  {
    "_id": 5,
    "name": "ABCDFE",
    "parentID": null
  }
]

how can i query find only Folder1 and children of Folder1 but ignore Folder2 in mongoDB like this by nodejs expressjs:

{ "_id": 1, "name": "ABC", "parentID": null }, { "_id": 2, "name": "ABC.txt", "parentID": 1 }, { "_id": 3, "name": "ABCD", "parentID": 1 }, { "_id": 4, "name": "ABC 3", "parentID": 3 } ]

This is my code:

exports.getProofFolderById = async (req, res, next) => {
  const file = await Proof.find({ _id: req.params.id})
  if(!file) {
    next(new Error("Folder not found!!!"))
  }
  res.status(200).json({
    success: true,
    file
  })
}

Thanks for help me ❤️

1 Answers

You can't have two documents with the same _id, so I assume you want to find the parent by its name.

One option for the query is using $lookup:

db.collection.aggregate([
  {$match: {name: "Folder1"}},
  {$lookup: {
      from: "collection",
      localField: "_id",
      foreignField: "parentID",
      as: "children"
    }
  },
  {$project: {
    children: {$concatArrays: [
          "$children", [{_id: "$_id", name: "$name", parentID: "$parentID"}]
        ]
      }
  }},
  {$unwind: "$children"},
  {$replaceRoot: {newRoot: "$children"}}
])

See how it works on the playground example

Related