我试图通过定义/导出模型并在控制器中使用该模型来遵循MVC模式。但是,出现错误:TypeError:ItemModel不是构造函数。
我已经关注了其他几个示例,但无法了解为什么会发生此错误。
文件结构如下:
src \ db_test.js
src \ controller \ Item.js
src \ models \ Item.js
const mongoose = require('mongoose');
const ItemSchema = new mongoose.Schema({
"name": String
});
var ItemModel = mongoose.model('Item', ItemSchema);
module.export = ItemModel;
controller \ Item.js
var ItemModel = require('../models/Item');
var itemController = {};
itemController.save = function(obj) {
var model = new ItemModel(obj); // Error here
model.save(function(err, item) {
if (err) {
console.log('Failed to save');
return;
}
console.log('saved successfully!');
});
}
module.exports = itemController;
db_test.js
const ItemController = require('./controller/Item');
var testItem = {
"name": "ItemName"
};
ItemController.save(testItem);
输出:
\src\controller\Item.js:18
var model = new ItemModel(obj); // Error here
^
TypeError: ItemModel is not a constructor
at Object.itemController.save (\src\controller\Item.js:5:4)
at Object.<anonymous> (\src\db_test.js:7:6)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
答案 0 :(得分:0)
我认为有一封遗失的信。
Item.js
module.export = ItemModel
更改
module.exports = ItemModel