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?
The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.
Mongoose, a neat ODM library for MongoDB used in Node. js projects, has plenty of useful features that make developers' lives easier. It manages relationships between data, has schema validation, and overall allows coding 3-5 times faster.
After having a model, we can use method find() on the model of a particular collection to get documents of the collection. <query>: It is optional. It specifies a selection filter that is used to filter documents using various MongoDB query operators. If not passed, all the documents are returned.
So, basically, the id getter returns a string representation of the document's _id (which is added to all MongoDB documents by default and have a default type of ObjectId ). Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an ObjectId or a string ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With