Juan Campa Juan Campa - 22 days ago 18
Node.js Question

Mongoose - Same schema for different collections in (MongoDB)

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.



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 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.