Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 281
Juan Campa Avatar asked Nov 12 '12 01:11

Juan Campa


People also ask

Are there any benefits to having a schema for different collections?

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.

Can we create multiple collections in MongoDB?

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.

Does Mongoose automatically create collection?

exports = mongoose. model('User',{ id: String, username: String, password: String, email: String, firstName: String, lastName: String }); It will automatically creates new "users" collection.

What is Mongoose schema ObjectId?

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.


1 Answers

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.

like image 129
JohnnyHK Avatar answered Sep 28 '22 17:09

JohnnyHK