Reputation: 2665
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
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
Reputation: 17014
Whatever.collection.insert
Upvotes: 3