Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define schema in MongoDB?

Tags:

mongodb

I know MongoDB is schemaless. However, I have data model for some objects/entities and I have a well defined set of attributes that they will contain. For eg, If I have a Student entity, I know its json looks like

{
  name: "string",
  id: "int",
  class: "string"
}

Is it possible to define this schema using MongoDB? If this isn't possible, then how can I validate if the user has sent the complete set for creating a new student?

like image 595
Megha Dev Avatar asked Apr 16 '15 09:04

Megha Dev


2 Answers

Mongodb is not a magical solution which work for all problems. One of it's strength is schemaless, so if you have collections that have absolutely fixed schema - then consider using other sql dbs (you will get rid of a lot of overhead).

If you really want to define schema - it is not possible to do this in vanilla mongo, but as with many popular technologies there are a loot of libraries available. One of them which allows to define schema is Mongoose. It is not the only one and you will find a lot of similar tools.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var blogSchema = new Schema({
  title:  String,
  author: String,
  body:   String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs:  Number
  }
});

P.S. if you do not want to use any additional library, you can define your schema in your application layer and validate each document before adding it to db, but before jumping into a new technology, it is nice to see whether it makes a good fit. Using technology for the sake of using technology is never a good idea.

like image 110
Salvador Dali Avatar answered Sep 21 '22 19:09

Salvador Dali


MongoDb by definition is a schema less database, so there is no way from the database end to verify that the user has sent the complete set or not.

For implementing this requirement you will need to implement it at the Application layer and make your application schema aware.

like image 33
vishad Avatar answered Sep 20 '22 19:09

vishad