madhums / node-express-mongoose-demo

A simple demo app using node and mongodb for beginners (with docker)

Home Page:https://nodejs-express-demo.fly.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

wzup opened this issue · comments

commented

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)));
  1. No module.exports:
// app/models/user.js

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

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.