Bee San
Bee San

Reputation: 2665

'Storing' a Mongoose Schema/Model (not the document) for future use

Problem: I'm making a web service that allows developers to 'register' their Mongoose schemas - they'll create JSON schemas in the browser, which will then be AJAX'ed to my server.

So I'll create a new Mongoose model using the submitted schema, but now I need this schema to be existent even when I restart the server.

I have code that does something like:

/* schemaObj is what you create a schema with,
   for example { name: String, id: Number } */

registerSchema = function(model_name, schemaObj) {
    desiredSchema = new Schema(schemaObj);
    desiredCollection = 'collection_' + model_name;
    mongoose.model(desiredCollection, desiredSchema, desiredCollection);
}

Ok, so this created a model for us with the custom schema.

Now my problem is that after I run this code, create a model, and then restart the server, the new collection/model wouldn't exist - because apparently a collection is created only when a document is saved - and I don't want to save a document right now (because I don't have any), just create a collection.

Question: Is there a way to create a collection with this 'fixed' schema - so that future docs that will be inserted should strictly conform to the schema? I'm basically looking for something like create table in SQL.

Upvotes: 3

Views: 1017

Answers (2)

federico carrara
federico carrara

Reputation: 31

I'm also working on an application like yours, where users can create their schemas, which are then automatically loaded in Mongoose. I created a function that checks if a schema is loaded in Songoose before you use it, and if it's not loaded (for example after a restart of the application) it loads it.

I have no documentation yet, but you can find my implementation in this jslModel.js file. Search for function loadMongooseModel.

Upvotes: 0

Jamund Ferguson
Jamund Ferguson

Reputation: 17014

  1. You cannot create a collection with a fixed schema in Mongo. This is explicitly a feature.
  2. As long as you've registered your new Schema with Mongoose before you try to use it, it should work just fine, whether or not the collection exists.
  3. Mongoose schema's are only sort-of enforced anyway, you can still sneak stuff by dropping down to the native driver, which is really easy. Whatever.collection.insert
  4. You need to re-register your schemas EACH TIME you start the server

Upvotes: 3

Related Questions