如何在 node-express js 中包含模型?
How to include a model in node-express js?
我正在尝试使用产品创建一个项目 table,我创建了架构,但是当我尝试将模型包含到我的控制器中时,它出现了错误。
从基本的 express 项目,我创建了控制器和模型文件夹。
我的控制器,
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);
}
});
};
型号,
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');
错误
TypeError: Products is not a constructor
文件结构,
File structure:
models
products.model.js
controllers
products.controller.js
app.js
在您的模型中更改此行:
mongoose.model('products', productSchema, 'products');
对此
module.exports = mongoose.model(‘Product’, productSchema);
在你的控制器中:
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);
}
});
};
我正在尝试使用产品创建一个项目 table,我创建了架构,但是当我尝试将模型包含到我的控制器中时,它出现了错误。
从基本的 express 项目,我创建了控制器和模型文件夹。
我的控制器,
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);
}
});
};
型号,
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');
错误
TypeError: Products is not a constructor
文件结构,
File structure:
models
products.model.js
controllers
products.controller.js
app.js
在您的模型中更改此行:
mongoose.model('products', productSchema, 'products');
对此
module.exports = mongoose.model(‘Product’, productSchema);
在你的控制器中:
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);
}
});
};