如何正确引用其他架构?
错误:
MissingSchemaError: Schema hasn't been registered for model "CategorySub".
模型文件:
// module dependencies
var mongoose = require('mongoose')
, Schema = mongoose.Schema
, CategoryMain = mongoose.model('CategoryMain')
, CategorySub = mongoose.model('CategorySub');
// set up the schema
var CategoryProductSchema = new Schema({
name: { type: String },
_category_main : [CategoryMainSchema],
_category_sub : [CategorySubSchema]
},
{
collection: 'categories_product'
}
)
// before save function equivalent
CategoryProductSchema.pre('save', function(next){
var now = new Date();
this.updated_at = now;
if ( !this.created_at ) {
this.created_at = now;
}
next();
})
CategoryProductSchema.set('toObject', { getters: true });
mongoose.model('CategoryProduct', CategoryProductSchema);
修改
这是我接手的一个小项目,我是MongoDB / Mongoose的新手。我在之前的所有者的app.js中找到了这个:
//load models
var models_path = __dirname + '/models/'
fs.readdirSync(models_path).forEach(function (file) {
if(~file.indexOf('.js')){
require(models_path + '/' + file);
}
})
它只是遍历文件夹并逐个注册每个模式。但是,在我的子模式的文件夹中,我的父模式之前,所以它首先被注册。
我添加了models.js
个文件,如下所示:
var models = ['token.js',
'user.js',
'category_main.js',
'category_sub.js',
'category_product.js',
'product.js'
];
exports.initialize = function() {
var l = models.length;
for (var i = 0; i < l; i++) {
require(models[i]);
}
};
然后替换app.js中的初始代码来调用require这样的新模型文件:
require('./models/models.js').initialize();
我从这个热门问题的答案中得到了这个想法:
但是,现在我从ReferenceError: CategoryMainSchema is not defined
模型文件中获得了category_sub.js
。
然而,它不是MissingSchemaError
。
答案 0 :(得分:0)
您的架构未定义以防万一。您的model.js和app.js只是浏览您定义的每个模型。这与在CategoryProduct的模型文件中具有CategorySubSchema的可见性不同。
在NodeJS中,您定义的架构和模型不会全局范围。您遇到的问题是范围问题,因为您假设模式是全局可见的。您必须将它们导出为其他功能才能看到它们。
请在此处引用nodejs module_export链接:http://nodejs.org/api/modules.html#modules_module_exports
在您的情况下,您可能需要将代码更改为模型文件中的以下内容:
exports.CategoryMainSchema = CategoryMainSchema;
每个模型文件中的等等。然后,在模型文件中,您希望将它们用作子模式,您可以要求使用以下模型:
var CategoryMainSchema = require('CategoryMain').CategoryMainSchema //assuming CategoryMain is the name of your model file
语法可能有点偏,但请试一试。谢谢。