简体   繁体   中英

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.

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);
     }
  });
 }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM