【问题标题】:How to include a model in node-express js?如何在 node-express js 中包含模型?
【发布时间】:2019-01-31 21:41:41
【问题描述】:

我正在尝试使用 products 表创建一个项目,我创建了架构,但是当我尝试将模型包含到我的控制器中时,它会引发错误。

从基本的 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

【问题讨论】:

    标签: node.js mongodb express mongoose mean-stack


    【解决方案1】:

    在您的模型中更改此行:

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

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 2016-02-04
      • 2015-08-21
      • 2015-02-05
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 2017-02-16
      相关资源
      最近更新 更多