cbnz
cbnz

Reputation: 674

Is it possible to search multiple Mongoose models at once?

I have four Mongoose models, SoleTrader, Partnership, Company and Trust. They’re different enough that I can’t merge them all into one schema, yet similar enough that I regularly need to query or make changes to all 4 types at once and rarely care which sort they are.

Is there a way of doing this – possibly by putting all four types in a single collection – without making four database calls each time?

Upvotes: 5

Views: 3636

Answers (1)

robertklep
robertklep

Reputation: 203419

Since you're using mongoose-schema-extend, it seem like you could create a simple 'base' schema and extend your other schema's off that. If you want to search across all of them, use the base model.

For instance:

// base schema
var PersonSchema = new Schema({
  name : String
}, { 
  collection       : 'users', // everything will get saved in the same collection
  discriminatorKey : '_type' 
});

// two schema's that extend off it
var EmployeeSchema = PersonSchema.extend({ department : String });
var EmployerSchema = PersonSchema.extend({});

// materialize all three into models
var Person    = mongoose.model('Person',   PersonSchema);
var Employee  = mongoose.model('Employee', EmployeeSchema);
var Employer  = mongoose.model('Employer', EmployerSchema);

...

// create some people
new Employee({
  name       : 'Homer Simpson',
  department : 'Safety'
}).save(...);

new Employer({
  name : 'Charles Montgomery Burns',
}).save(...);

...

// search across employers and employees
Person.find({ ... }, function(err, people) {
  ...
});

However, I have to say that the advertised behaviour of find() returning the correct model instance according to the discriminator key doesn't work for me.

Upvotes: 5

Related Questions