I have the following schema and route set up. I cannot post request further into the nested child. Ideally, I want to be able to post request like the following (post to 3 results in id 4 child). Any help is appreciated.
Edit: Is it even possible without recursively findOne through each index like findOne at top -> findOne at child -> findOne at child2 till it finds matching id? Is restructuring database to make it flat and adding parentID key the only way?
[
{
{
id:1,
child: [
{
id:3,
child: [
{
id:4,
child:[]
}
]
}
]
}
id:2,
child:[]
}
]
MongoDB JSON
[
{
"_id": "6050036c5138b72ad07267e5",
"title": "dddd",
"completed": true,
"__v": 1,
"child": [
{
"_id": "60518f6c497c2f59a4161ac5",
"title": "gooooood",
"completed": false,
"child": []
//Cannot post request here with _id="60518f6c497c2f59a4161ac5"
}
]
}
]
task-model.ts
import mongoose from "mongoose";
export const taskSchema = new mongoose.Schema(
{
title: { type: String, required: true },
completed: { type: Boolean, required: true },
},
);
taskSchema.add({ child: [taskSchema] });
export const Task = mongoose.model("Task", taskSchema);
route.ts
router.route("/:id").post((req, res) => {
Task.updateOne(
{ _id: req.params.id },
{ $push: { child: req.body.child }},
)
.then(() => res.json("task added"))
.catch((err) => res.status(400).json("Error" + err));
});