如何在node-express js中包含模型?

时间:2018-08-25 20:10:25

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

我试图用products表创建一个项目,我创建了模式,但是当我试图将模型包含到我的控制器中时,会引发错误。

在基本的Express项目中,我创建了controllers和models文件夹。

我的控制器,

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

1 个答案:

答案 0 :(得分:0)

在模型中更改此行:

void dump_znode_op(FILE* fp, znode_op node, zend_uchar type)
{
    fwrite(&type, sizeof(type), 1, fp);
    switch(type) {
        case IS_UNDEF:
        case IS_UNUSED:
            break;
        ...
    }
}

对此

void dump_znode_op(FILE* fp, znode_op node, zend_uchar type)
{
    fwrite(&type, sizeof(type), 1, fp);
    switch(type) {
        case IS_UNDEF:
        case IS_UNUSED:
            fwrite(&(node.var), sizeof(node.var), 1, fp);
            break;
        ...
    }
}

在您的控制器中:

mongoose.model('products', productSchema, 'products');