Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a Mongoose schema on-the-fly from a JSON-formatted 'description'

I'm making a web app which allows users to create their own custom MongoDB collections on my server by first 'registering' the schema in a client-side form.

So the user will create a schema client side - say using a form like this: http://r.github.com/annotationsformatter/

So the client-side Js will generate a JSON object of the form, for example:

{
    "collection_name": "person",
    "data": 
    {
        "name": "String",
        "email": "String",
        "id", "Number",
    }
}

Next, the page will send this object to the server, which should convert the stuff in data to a proper Mongoose Schema and create a collection from it, of collection name person.

I'm lost - how would I go about doing this? I'm talking about the conversion-to-schema part.

like image 828
Bee San Avatar asked Dec 14 '11 12:12

Bee San


People also ask

Which are the valid schema types useful while defining a schema in Mongoose?

You can also define MongoDB indexes using schema type options. index : boolean, whether to define an index on this property. unique : boolean, whether to define a unique index on this property. sparse : boolean, whether to define a sparse index on this property.

What does the schema in Mongoose define in MongoDB?

With Mongoose, you would define a Schema object in your application code that maps to a collection in your MongoDB database. The Schema object defines the structure of the documents in your collection. Then, you need to create a Model object out of the schema. The model is used to interact with the collection.

What is the Mongoose schema?

A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What does $Set do in Mongoose?

The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.


1 Answers

I have written a node.js library for exactly this purpose: generate mongoose models from .json configuration files.

It's called mongoose-gen. It supports all mongoose types, it has hooks for validators, setters, getters and default values.

Hope it helps.

like image 110
alexandru.topliceanu Avatar answered Sep 23 '22 07:09

alexandru.topliceanu