Onur Önder
Onur Önder

Reputation: 311

How to Mongoose add Parent-Child Category(Nested) Node.JS

I would like to add parent-child categories using mongoose with Nodejs.Data is being added.but added child id gets the same as parent.How do I set child id as identity. Can you help me?

category model

var childSchema = new Schema({name:String,_id:{type:Schema.ObjectId}});
var categoryschema = new Schema({
 _id: { type: Schema.ObjectId, auto: true },
 name:  String,
 children: [childSchema]  
});

API

exports.addCategory = function(req,res){
var newCategory = new category(req.body);

 if(req.body._id==undefined){        
    newCategory.save((err)=>{
        if (err) return handleError(err);           
        res.send("insertad");
    });
}else{        
    req.body._id = Schema.ObjectId;
    category.findByIdAndUpdate(req.body._id,{ $set: { children:req.body } },{new: true},function(err, model){
        if(err)
        console.log("error",err);           
        res.send("update");
    });
  }

}

Upvotes: 2

Views: 1413

Answers (1)

Şivā SankĂr
Şivā SankĂr

Reputation: 2036

In your code category.findByIdAndUpdate(req.body._id,{ $set: { children:req.body } } your are finding and updating document with the same ObjectId. So it should be,

{ $set: { children: { "_id": mongoose.Types.ObjectId(), 'name': req.body.name } } }

Alternative,

Simply remove _id from your schema, You will get auto generated ObjectId automatically.

var childSchema = new Schema({name:String});

Upvotes: 3

Related Questions