I'm creating an application (Express+MongoDB+Mongoose) where documents are naturally clustered by groups. Every query to the database will only need to access documents from a single group. So I'm thinking it's a good idea to separate each group into its own collection for the sake of performance.
Now, I'm going to use the same Schema for each of these collections because they will store the same type of documents. I used to have a single Model object because I used to have everything in a single collection but now I need multiple Models, one per group.
Is it a good idea to create a new Model object on every request (using a shared Schema) or is this too expensive? What would be a good architectural decision in this case?
The best approach I could think of is to create a Model the first time there's a request for a collection and then cache the Models in a dictionary for quick access.
I guess the best approach depends on the cost of creating a new Model object on each request.
Thanks!
You will need to create multiple class schemas for each collection i.e. and then work out which schema to use for the client. There is no benefit to this approach and you are simply creating complications and further challenges when you attempt to join and query these relationships.
As mentioned above, a single database can have multiple collections. The following creates multiple collections. Use the show collections commands to list all the collections in a database. To delete a collection, use the db.
exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.
ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
Models are already cached by Mongoose and you can use the same schema object for multiple models/collections. So just create your set of models once (at startup) using code like:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({...});
var model1 = mongoose.model('model1', schema);
var model2 = mongoose.model('model2', schema);
If you don't want to pass around the model1
, model2
model instances, you can look them up as needed by calling mongoose.model('model1');
in your handlers.
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