What is the advantage of reading MongoDB models from a file over requiring them as an object?
wzup opened this issue · comments
wzup commented
Could you please elaborate on that?
- No
require('./userModel')
:
// server.js
// Bootstrap models
fs.readdirSync(models)
.filter(file => ~file.search(/^[^\.].*\.js$/))
.forEach(file => require(join(models, file)));
- No
module.exports
:
// app/models/user.js
const mongoose = require('mongoose');
mongoose.model('User', UserSchema);
Amr Ragaey commented
1.the code dynamically requires any new model as it filter the extensions with .js in the 'models' directory, otherwise you'll have to require them one by one explicitly.
2.Both works, but it's preferred to call the model from mongoose object. In some cases, assume you need to call another file in your model and the file uses the model, you will have circular dependency problem. So this is safer.