1

You can retrieve a Mongoose model like so:

let User = mongoose.model('User');

I am looking to do get an associative array of these models. Is there some clever way of getting a list of models using object destructuring? Something like:

const {User, Employees, Managers} = mongoose.model('x');

My current solution is to do this:

/project
  /models
    index.js

where index.js looks like:

module.exports = {
  User: require('./user'),
  Employee: require('./employee'),
  Manager: require('./manager'),
};

Where the user.js, employee.js and manager.js files just look like:

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

let userSchema = new Schema({...});

module.exports = mongoose.model('User', userSchema, 'users');

Then I can do this:

 const {User, Employees, Managers} = require('./models');

But I am looking for a better solution that requires no manual work if possible.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

2
const models = {};
mongoose.modelNames().forEach(function(modelName){
    models[modelName] = mongoose.model(modelName);
});
console.log(models); 
Talha Awan
  • 4,573
  • 4
  • 25
  • 40
  • that will work, but in order to avoid simple race conditions, I may still have to manually import each model above your code here. – Alexander Mills Jun 07 '17 at 21:31
  • Can you give an example of a race condition? I think you don't need to import files independently and models can be accessed and safely used with above code. I may be wrong. – Talha Awan Jun 07 '17 at 22:33
  • The load order of files is pretty complex in our app and most real apps. Would have to ensure that all models load, before any code calls the code in your answer..not that easy. – Alexander Mills Jun 08 '17 at 01:02
  • Using my original method, with an index.js file referencing all the models, then I can guarantee that the models have all loaded already. – Alexander Mills Jun 08 '17 at 01:04
  • @AlexanderMills What do you think you mean by "load order"? Once "required" and therefore "registered with mongoose" then the content is available in `mongoose.models` as is shown in the technique here. It generally looks like you are trying to emulate ES6 imports and exports, for which then you probably "should" be using ES6 syntax rather than trying to emulate it. In the context of the question asked, then this would appear to be correct. – Neil Lunn Jun 08 '17 at 04:41