简体   繁体   中英

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.

Thanks!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM