簡體   English   中英

無法推送數據一對多關系(nodejs,mongodb)

[英]Can't Push data One to Many Relation (nodejs ,mongodb)

我正在嘗試將數據插入 MongoDB 數據庫,但我收到此錯誤無法讀取未定義的屬性“推送”。

我不明白我的代碼中有什么問題。 請幫我解決問題。 我是一名學生,正在學習它。

在這里,我試圖將服務推入 Model 類別。 為此,我在服務和類別之間創建了一對多的關系。 但我無法將服務推入該類別。

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;

這是我的服務 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");
    });
},

這樣做:

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

},

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM