Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

javascript - 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");
    });
},
question from:https://stackoverflow.com/questions/65868279/cant-push-data-one-to-many-relation-nodejs-mongodb

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
  }

},

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...