MongoDB: How to define a schema?

You don't create collections in MongoDB.
You just start using them immediately whether they “exist” or not.

Now to defining the “schema”. As I said, you just start using a collection, so, if you need to ensure an index, just go ahead and do this. No collection creation. Any collection will effectively be created when you first modify it (creating an index counts).

> db.no_such_collection.getIndices()
[ ]
> db.no_such_collection.ensureIndex({whatever: 1})
> db.no_such_collection.getIndices()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "test.no_such_collection",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "whatever" : 1
                },
                "ns" : "test.no_such_collection",
                "name" : "whatever_1"
        }
]

Create empty collection

This is how you could create empty collection in MongoDB using build in interactive terminal:
db.createCollection('someName'); // create empty collection

Just you don't really have to, because as someone pointed before, they will get created in real time once you start to interact with the database.

MongoDB is schema-less end of story, but ...

You could create your own class that interacts with mongo Database. In that class you could define rules that have to fulfilled before it can insert data to mongo collection, otherwise throw custom exception.

Or if you using node.js server-side you could install mongoose node package which allows you to interact with database in OOP style (Why bother to reinvent the wheel, right?).

Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

docs: mongoose NPM installation and basic usage https://www.npmjs.com/package/mongoose mongoose full documentation http://mongoosejs.com

Mongoose use example (defining schema and inserting data)

var personSchema = new Schema({
    name: { type: String, default: 'anonymous' },
    age: { type: Number, min: 18, index: true },
    bio: { type: String, match: /[a-zA-Z ]/ },
    date: { type: Date, default: Date.now },
});

var personModel = mongoose.model('Person', personSchema);
var comment1 = new personModel({
    name: 'Witkor',
    age: '29',
    bio: 'Description',
});

comment1.save(function (err, comment) {
    if (err) console.log(err);
    else console.log('fallowing comment was saved:', comment);
});

Wrapping up ...

Being able to set schema along with restriction in our code doesn't change the fact that MongoDB itself is schema-less which in some scenarios is actually an advantage. This way if you ever decide to make changes to schema, but you don't bother about backward compatibility, just edit schema in your script, and you are done. This is the basic idea behind the MongoDB to be able to store different sets of data in each document with in the same collection. However, some restriction in code base logic are always desirable.

Tags:

Mongodb