Dynamically create collection with Mongoose

mongoose, node.js

Solution

From mongo docs here: data modeling

In certain situations, you might choose to store information in several collections rather than in a single collection.

Consider a sample collection logs that stores log documents for various environment and applications. The logs collection contains documents of the following form:

{ log: "dev", ts: ..., info: ... } { log: "debug", ts: ..., info: ...}

If the total number of documents is low you may group documents into collection by type. For logs, consider maintaining distinct log collections, such as logs.dev and logs.debug. The logs.dev collection would contain only the documents related to the dev environment.

Generally, having large number of collections has no significant performance penalty and results in very good performance. Distinct collections are very important for high-throughput batch processing.

Problem

I want to give users the ability to create collections in my Node app. I have really only seen example of hard coding in collections with mongoose. Anyone know if its possible to create collections dynamically with mongoose? If so an example would be very helpful. Basically I want to be able to store data for different 'events' in different collections. I.E. Events: event1, event2, ... eventN Users can create there own custom event and store data in that collection. In the end each event might have hundreds/thousands of rows. I would like to give users the ability to perform CRUD operations on their events. Rather than store in one big collection I would like to store each events data in a different collection. I don't really have an example of what I have tried as I have only created 'hard coded' collections with mongoose. I am not even sure I can create a new collection in mongoose that is dynamic based on a user request. ``` var mongoose = require('mongoose'); mongoose.connect('localhost', 'events'); var schema = mongoose.Schema({ name: 'string' }); var Event1 = mongoose.model('Event1', schema); var event1= new Event1({ name: 'something' }); event1.save(function (err) { if (err) // ... console.log('meow'); }); ``` Above works great if I hard code 'Event1' as a collection. Not sure I create a dynamic collection. ``` var mongoose = require('mongoose'); mongoose.connect('localhost', 'events'); ... var userDefinedEvent = //get this from a client side request ... var schema = mongoose.Schema({ name: 'string' }); var userDefinedEvent = mongoose.model(userDefinedEvent, schema); ``` Can you do that?

Original source

Related problems