How to Node JS- MongoDB & Mongoose

In this guide, we’re going to learn through how to connect to a MongoDB database with Node JS using Express JS and Mongoose which are two of the most popular frameworks.

Mongoose is a Node.js library that provides MongoDB object mapping similar to Object Relational Mapping (ORM) with a familiar interface within Node.js. ORM or ODM (Object Data Mapping) in the case of Mongoose. Mongoose allows you to access to the MongoDB commands for CRUD. To use mongoose, make sure that you add it to you Node project by using the following npm command.

$ npm install mongoose --save


Connecting to MongoDB

To connect MongoDB using mongoose, use the following code.


	//import the mongoose to project
	var mongoose = require('mongoose');

	var db = mongoose.connection;

	db.on('error', console.error);
	db.once('open', function() {
	  // Schemas and models are here.

	//To connect to a MongoDB database (either local or hosted)


Schemas and Models

To start CRUD application, we need a mongoose schema and a model to work with the data that will be persisted in our MongoDB database. Schemas define the structure of documents within a collection and models are used to create instances of data that will be stored in documents. Mongoose Methods can also be defined on a mongoose schema.


		// create a schema
	var userSchema = new Schema({
		  name: String,
		  username: { type: String, required: true, unique: true },
		  password: { type: String, required: true },
		  location: String,
		  created_at: Date

	// the schema is useless so far
	// we need to create a model using it
	var User = mongoose.model('User', userSchema);

	// make this available to our users in our Node applications
	module.exports = User;

This is how a Schema is defined. We must grab mongoose and mongoose.Schema. Then we can define our attributes on our userSchema for all the things we need for our user profiles.


Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...