[英]MissingSchemaError: Schema hasn't been registered for model
如何正确引用另一个模式?
错误:
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
模型文件中ReferenceError: CategoryMainSchema is not defined
。
但是,这不是MissingSchemaError
。
未定义您的架构,以防万一。 您的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
语法可能有点偏,但请试一试。 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.