我的代码如下所示,并使用邮递员为我获取“消息”:“Product is not a constructor”
。路由器似乎配置正确,但现在我不知道问题出在哪里。文件Product Constructor
放置在正确的方向。当运行节点服务器
时,终端中没有出现错误。
产品构造函数
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
price: Number
});
module.export = mongoose.model('Product', productSchema);
岗位路由器
const mongoose = require('mongoose');
const Product = require('../models/product'); //import schema, product constructor
//POSTs to products
router.post('/', (req,res,next) => {
//ObjectId method to add new ID
const product = new Product({
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
price: req.body.price
});
//mongoose method to save data
product
.save()
.then(result => {
console.log(result);
})
.catch(err => console.log(err));
res.status(201).json({
message: 'sending POSTs to /products',
createdProduct: product
});
});
它应该是module.exports
(doc),而不是module.export
:
module.exports = mongoose.model('Product', productSchema);
现在,您的模块实际上导出了一个默认值(一个空对象)。
作为旁注,Schema被期望用作构造函数。而函数本身的编写方式是,如果在不使用new
的情况下使用,它将使用正确的语法回忆自己:
if (!(this instanceof Schema)) {
return new Schema(obj, options);
}
。。。您可以避免这种(尽管很小)性能损失,更重要的是,可以清楚地显示实际意图:
const productSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
price: Number
});
可能您应该创建模式的实例
const productSchema = /*(this --->)*/ new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
price: Number
});