madhums / node-express-mongoose-demo

A simple demo app using node and mongodb for beginners (with docker)
https://nodejs-express-demo.fly.dev
MIT License
5.12k stars 1.38k forks source link

What is the advantage of reading MongoDB models from a file over requiring them as an object? #225

Closed wzup closed 5 years ago

wzup commented 7 years ago

Could you please elaborate on that?

  1. No require('./userModel'):
    
    // server.js

// Bootstrap models fs.readdirSync(models) .filter(file => ~file.search(/^[^.].*.js$/)) .forEach(file => require(join(models, file)));


2. No `module.exports`:

// app/models/user.js

const mongoose = require('mongoose'); mongoose.model('User', UserSchema);

amragaey commented 7 years ago

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.