javascript - 如何解决这个“错误一旦编译就无法覆盖模型”?
问题描述
我是节点 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
解决方案
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
推荐阅读
- intellij-idea - 黄瓜报告在带有 inteliij 的黄瓜的控制台中显示 Given 而不是 And
- c - C中的预处理器
- flutter - 如何通过将从 api 获取的数据作为 pageno 传递来在颤动中进行滚动控制
- c - 指针和整数之间的警告数组比较
- java - Spring 和 JavaMail 连接超时
- c# - 如何从 Asp.Net Core 的 DBContext 文件中的 appsettings.json 读取连接字符串?
- python - Beautifulsoup 正在返回双链接
- jquery - 没有缓存 jQuery 文件时,网站加载速度更快?
- java - Apache http客户端自签名证书
- angular - 滚动时底部垫子工具栏闪烁