Salar
Salar

Reputation: 5509

How do I store a mongoose schema in the database

I'm developing an special app with express and mongoose that needs to build a mongoose schema and then store it in database. I want to create a project that people can create collections dynamically at run time and then ask the others to fill those collections via special forms

For example I would like to store a schema such as the one below into my database. How can I do that?

var entitySchema = {
    name : String,
    num : [Number],
    time : [Date]
} ;

Is there any special function that converts mongoose schemas to json or string?
calling toString() function on the schema json, does not work, because it can't interpret the String or Number types

Upvotes: 3

Views: 2210

Answers (1)

Andrew Lavers
Andrew Lavers

Reputation: 8151

Mongoose schemas use function propreties like Date and its own types such as Schema.Types.Mixed to define schemas, and MongoDB won't know how to store such things, so you'll have to do some additional serialization/deserialization legwork to make that work. For example, converting functions into strings when saving the schema eg Date-->"Date" and restoring the proper Date function back again when reading the schema back to mongoose. You would need to recurse through your schema structure to look for problematic properties and make such modifications. This is doable but there are other perhaps better options if you don't need the extra funcionality that mongoose offers (like index generation, pre/post middleware, etc).

You might consider using JSON schemas instead. A popular library for this is tv4.

JSON schemas can be stored in mongoDB without changes and you can use the same schema lib on both the client and server. JSON schema parsing engines also give you more options with respect to validation, such as better error messages.

Upvotes: 1

Related Questions