How to reference another schema properly?
Error:
MissingSchemaError: Schema hasn't been registered for model "CategorySub".
Model file:
// 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);
EDIT
This is a small project I took over, and I'm new to MongoDB/Mongoose. I found this in app.js from the previous owner:
//load models
var models_path = __dirname + '/models/'
fs.readdirSync(models_path).forEach(function (file) {
if(~file.indexOf('.js')){
require(models_path + '/' + file);
}
})
It simply goes through the folder and registers each schema one by one. However, in the folder my child schema is before my parent schema, so it's getting registered first.
I added a models.js files that looks like this:
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]);
}
};
And then replaced the initial code in app.js to call require this new models file like so:
require('./models/models.js').initialize();
I got this idea from one of the answers in this popular question:
However, now I'm getting a ReferenceError: CategoryMainSchema is not defined coming from my category_sub.js model file.
It's not a MissingSchemaError, however.
Aucun commentaire:
Enregistrer un commentaire