首页 > 解决方案 > 如何解决这个“错误一旦编译就无法覆盖模型”?

问题描述

我是节点 js 的初学者,我提出了一些问题,但我无法弄清楚
这是我的模型 product.js,我在其中定义了产品模式,其中添加了一些变量和属性

const mongoose =require("mongoose");
const {ObjectId} = mongoose.Schema;

const productSchema = new mongoose.Schema({
name:{
    type:String,
    trim:true,
    required:true,
    maxlength:32,
},
description:{
    type:String,
    trim:true,
    required:true,
    maxlength:2000
},
price:{
    type:Number,
    required:true,
    maxlength:32,
    trim:true,
},
category:{
    type:ObjectId,
    ref:"Category",
    required:true
},
stock:{
    type:Number
},
sold:{
    type:Number,
    default:0
  },
  photo:{
    data: Buffer,
    contentType: String
  }
 },{timestamps:true});

 module.exports = mongoose.model("Product", productSchema);  

这是我的控制器 product.js 在为产品模型定义模型时出现此错误

const Product = require("../models/product");//here is getting error 
const formidable = require("formidable");
const _ = require("lodash");
const fs = require('fs');

exports.getProductById = (req , res, next,id) => {
 Product.findById(id)
 .populate("category")
  .exec((err , product )=>{
  if(err){
    return res.status(400).json({
      error:"Product not found"
    })
  }
  req.product = product;
  next();
 })
};

 exports.createProduct = (req , res)=>{
  let form = new formidable.IncomingForm();
   form.keepExtensions = true;

   form.parse(req , (err,fields,file) => {
    if(err){
      return res.status(400).json({
        error:"Problem with image"
      });

    }

    //destructuring
    const {name, description,price,category,stock,photo} = fields;


    //restrications 
    if(!name ||
       !description ||
       !price ||
       !category ||
       !stock 
       ){
        return res.status(400).json({
          error:"please include all fields"
        })
    }

    let product = new Product(fields);
    //handel the file
    if(file.photo){
      if(file.photo.size > 3000000){
        return res.status(400).json({
          error:"file is too big"
        })
      }
      product.photo.data = fs.readFileSync(file.photo.path)
      product.photo.contentType = file.photo.type;
    }

    //
    product.save((err , product)=>{
      if(err){
        res.status(400).json({
          error:"Saving tshirt in Db Failed"
        })
      }
      res.json(product);
    })
   });
  };

控制台错误如下 [1]:https://i.stack.imgur.com/yo1fd.png

标签: javascriptnode.jsexpress

解决方案


The error might lie in the way you are retrieving the objectId type. Try getting it this way:

category: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "category",
    required: true,                   
}

The problem you are getting is because you are trying to define the schema twice


推荐阅读