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

Issue

This Content is from Stack Overflow. Question asked by Đạt Huỳnh

My json data in mongoDB, example:

{
 _id: 123,
 name: 'Folder1',
 parentID: null
},
{
 _id: 412,
 name: 'ABC.txt',
 data: Binary(...),
 parentID: 123
},
{
 _id: 512,
 name: 'CDF.txt',
 data: Binary(...),
 parentID: 123
},
{
 _id: 123,
 name: 'Folder2',
 parentID: null
},

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

{
_id: 123,
name: ‘Folder1’,
parentID: null
},
{
_id: 412,
name: ‘ABC.txt’,
data: Binary(…),
parentID: 123
},
{
_id: 512,
name: ‘CDF.txt’,
data: Binary(…),
parentID: 123
}

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 ❤️


Solution

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

This Question was asked in StackOverflow by Đạt Huỳnh and Answered by nimrod serok It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?

Exit mobile version