Skip to content
Advertisement

Can’t Push data One to Many Relation (nodejs ,mongodb)

I am trying to insert data into MongoDB database but I get this error Cannot read property ‘push’ of undefined.

I can’t understand what is the issue is here in my code. please help me with the solution. I am a Student and learning it.

here I am trying to push service into the category Model. for that, I have created a one to many relations between service and category. but I can’t push the services into the category.

Schema design for category & Service =======

    const mongoose = require("mongoose")
    const Schema = mongoose.Schema
    
    const CategorySchema = new Schema({
        name:{
            type:String,
            required:true
        },
        services:[
            {
            type:Schema.Types.ObjectId,
            ref:'Service'
        }
    ]
    
    },{ timestamps:true })
    
    const Category = mongoose.model("Cat", CategorySchema);
    module.exports = Category;
    
    
    service======
    const mongoose = require('mongoose')
    const Schema = mongoose.Schema
    
    const serviceSchema = new Schema({
        title:{
            type: 'String',
            required: true
        },
        description:{
            type: 'String',
            required: true
        },
        image: {
            type: 'String',
            required: true
        },
        price: {
            type: 'Number',
            required: true
        },
        category: {
            type:Schema.Types.ObjectId,
            ref:'Cat'
        }
    })
    
    const Service = mongoose.model("Service", serviceSchema);
    module.exports = Service;

here is my service controller

postService:(req, res)=>{
  const { title, price, description,category} = req.body;
  const image = req.file.filename;
  const service = new Service({
    title,
    price,
    category,
    description,
    image,
  });
  service.save()
  .then((service)=>{
      const category = Category.findOneAndUpdate({_id: service.category})
      category.services.push(service)
      category.save()
      console.log(category)
      return res.redirect("/admin/services");
    })
    .catch((err) => {
      console.log(err);
      return res.redirect("/admin/services/create");
    });
},

Advertisement

Answer

do like this:

postService: async(req, res)=>{
  const { title, price, description,category} = req.body;
  const image = req.file.filename;
  const service = new Service({
    title,
    price,
    category,
    description,
    image,
  });
  try {
    await service.save()
    let categoryModel = await Category.findById(category);//category should be an ObjectId
    categoryModel.services.push(service)
    await categoryModel.save()
    return res.redirect("/admin/services");
  } catch (err) {
    console.log(err);
    return res.redirect("/admin/services/create");
  }

},
Advertisement