CREATING SCHEMAS IN MONGODB USING MONGOOSE

Creating Schemas in MongoDB Using Mongoose

MONGOOSE
Mongoose is an “elegant MongoDB object modelling for Node.js “. If you have used MongoDB before and tried basic database operations, then you might have noticed that MongoDB is “schema-less”. When you are looking to implement a more structured database and want to leverage the power of MongoDB, Mongoose is one of the Object Data Mapping (ODM) solutions.

To quickly determine, run an insert command into a collection named users like the following:

Creating Schemas in MongoDB Using Mongoose

1db.users.insert({ name : ‘Arvind’, gender : ‘male’});

And right after that, you can run:

1db.users.insert({ name : ‘Arvind’, gender : ‘male’, password : ‘!@#$’});

MongoDB will never complain about the variation in the number of columns (key-value pairs). But when the user wants to keep the data more organized and controlled, the user would need to maintain that in server code, writing validation, making sure nothing unrelated is stored in a collection. This is where Mongoose makes task easy.

Mongoose provides a straight-forward, schema-based solution to modelling the application data and includes built-in typecasting, validation, query building, business logic hooks, and much more, out of the box.

In this article, we are going to show you how to use Mongoose for your MongoDB deployments to create a more straight-forward, schema-based solution to modelling your application data.

START DEVELOPING

After installing Node.js, create a new folder named “myMongooseApp” and open terminal/prompt and run:
1
npm init

This will help the user in setting a new node project. Fill it up as required. Next, install Mongoose as a dependency to the project and run;
npm install mongoose –save-dev
Then, start the MongoDB service by running:

Mongod

Then, create a new file named index.js at the root and then open it up in favorite editor. Add the below code:

var mongoose = require(‘mongoose’);
mongoose.connect(‘mongodb://localhost/myTestDB’);

var db = mongoose.connection;
db.on(‘error’, function (err) {
console.log(‘connection error’, err);
});
db.once(‘open’, function () {
console.log(‘connected.’);
});
Here, the user requires the Mongoose package to connect to the database and initialize the connection. The name of our database is myTestDB.
Then, run:
node index.js
The user should now see the connected message. The user can also use a node package named nodemon for automatically restarting the node server on changes.

MONGOOSE SCHEMA

Schemas are like skeletons of how the user data collection will look. If the user is dealing with a collection of customers, then the schema would look something like this:

Name – String
Age – Number
Gender – String
Date of Birth – Date

If the user is dealing with collection of products, then the schema would look like this:

SKU – String
Name – String
Price – Number
InStock – Boolean
Quantity – Number

The user can observe the drift. When the data is guarded with a schema, the probability of storing garbage data decreases drastically.

Now that we have got an understanding of schemas, let us try and build a user schema using Mongoose.

var Schema = mongoose.Schema;
var userSchema = new Schema({
name : String,
age : Number,
DOB : Date,
isAlive : Boolean
});

Then, create a model from the schema and add;
var User = mongoose.model(‘User’, userSchema);
The model is ready and now can use this as base schema to insert users into the database. This way, we know that every document in a user collection will have the fields listed on the schema. Now, let us create a new user instance and save it to DB.
var arvind = new User({
name : ‘Arvind’,
age : 99,
DOB : ’01/01/1915′,
isAlive : true
});

arvind.save(function (err, data) {
if (err) console.log(err);
else console.log(‘Saved : ‘, data );
});
The user should will find something like below:
Saved : { __v: 0,
name: ‘Arvind’,
age: 99,
DOB: Fri Jan 01 1915 00:00:00 GMT+0530 (IST),
isAlive: true,
_id: 536a4866dba434390d728216 }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>