Node.js connect to mongodb using mongoose

Home >> Blog >> Node.js connect to mongodb using mongoose
By Admin Sep 04, 2020

Node.js connect to mongodb using mongoose: following example shows how to connect to a MongoDB instance that is running on localhost using port 27017. If the database is omitted, the MongoClient uses the default test database.
Install MongoDB: (Skip if already Installed)
npm install mongodb --save
You may also like - MongoDB Interview Questions
Mongoose:
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node js.

In short, Mongoose provides a straight-forward, schema-based solution to model your application data. Mongoose is similar to an ORM (Object-Relational Mapper) used in RDBMS.

Step-1: Install Mongoose
npm install mongoose --save
Step-2: Include Mongoose (app.js/server.js/index.js)
// Include Mongoose using Node.js const mongoose = require('mongoose'); // Include Mongoose using ES6 import mongoose from 'mongoose';
Step-3: Create Database Schema

Each schema maps to a MongoDB collection and defines the shape of the documents within that collection

const mongoose = require('mongoose'); const Schema = mongoose.Schema; //Sample of User Schema var mySchema = new Schema({ name: String, email: String, address: String, age: { type: Number, min: 0 }, date: { type: Date, default: Date.now } });
Step-4: Create Model
var ModelName = mongoose.model('ModelName', mySchema); mongoose.connect('mongodb://localhost:27017/database'); //OR (using username and password) mongoose.connect('mongodb://username:password@localhost:27017/database');
Step-5: Check DB Connection
var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function(){ console.log("Successfully Connected to DB"); //do operations which involve interacting with DB etc. });

For more details - Mongoose Model Official Docs Link