[英]How to include a model in node-express js?
I am trying to create a project with products table,I created the schema but when I am trying to include the model into my contoller it trows the error. 我试图用产品表创建一个项目,我创建了模式,但是当我试图将模型包含到我的控制器中时,会引发错误。
From the basic express project,I created controllers and models folders. 在基本的Express项目中,我创建了controllers和models文件夹。
My controller, 我的控制器,
var mongoose = require('mongoose'),
Products = require('../models/products.model.js');
exports.addProduct = function( req, res ) {
var params = req.body;
var productsModel = new Products(params);
productsModel.save(function (error, response) {
if (error) {
return res.end(error);
}
if (response) {
res.json(response);
}
});
};
Model, 模型,
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
const productSchema = new Schema({
author: ObjectId,
name: String,
description: String,
price: Number,
quantities_available: Number
});
mongoose.model('products', productSchema, 'products');
error 错误
TypeError: Products is not a constructor
File structure, 文件结构
File structure:
models
products.model.js
controllers
products.controller.js
app.js
In your model change this line: 在模型中,更改以下行:
mongoose.model('products', productSchema, 'products');
To this 对此
module.exports = mongoose.model(‘Product’, productSchema);
In your controller: 在您的控制器中:
var mongoose = require('mongoose'),
Product = require('../models/products.model.js');
exports.addProduct = function( req, res ) {
var params = req.body;
var productsModel = new Product(params);
productsModel.save(function (error, response) {
if (error) {
return res.end(error);
}
else {
res.json(response);
}
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.