nitin.agam
nitin.agam

Reputation: 2142

Nested Mongoose Schema of same type

I have to create a mongoose schema. For example, I have a collection named "categories" in which parent categories are stored. And a parent category can have multiple sub-categories.

So the category structure is the same for the parent and child category.

Please help anyone how to create schema for this structure. A sample response is below:

{
"id": "category_id_123"
"name": "General",
"parent_id": null,
"childs": [
    {
        "id": "category_id_124",
        "name": "General Knowledge",
        "parent_id": "category_id_123",
    },
    {
        "id": "category_id_125",
        "name": "Math",
        "parent_id": "category_id_123",
    },
]
}

Upvotes: 2

Views: 330

Answers (1)

Ransaka Ravihara
Ransaka Ravihara

Reputation: 1994

This is the code that I accomplish similar task.

router.put('/addchild', (req, res, next) => {
    Parent.findById(
            req.headers.uid // Id of the parent
        )
        .then((parent) => {
            return parent.updateOne({
                $addToSet: {
                    child: req.body
                }
            }).then(() => {
                res.status(200).send({
                    message: 'child added'
                })
            })
        }).catch(() => {
            res.status(500).send({
                message: 'child adding error.'
            })
        })
})

Here is relevant schema structure

const mongoose = require('mongoose')

const Schema = mongoose.Schema
const parentSchema = new Schema({
     _id: {
    type: mongoose.Schema.Types.ObjectId,
    createIndex: true,
    required: true,
    auto: true
},
email: {
    type: String,
    required: true,
    unique: true,
    match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
},

child: [],

})
module.exports = mongoose.model('Parent', userSchema, 'parent')

Hope it will help you!

Upvotes: 1

Related Questions