Home >> Latest Articles >> Node js connect to mongodb using mongoose

Node js connect to mongodb using mongoose

Node js connect to mongodb using mongoose: following example shows how to connect to a MongoDB instance that is running on localhost using port no 27017. If the database is omitted, the MongoClient uses the default test database.
Install MongoDB before using:
npm install mongodb --save
var MongoClient = require('mongodb').MongoClient;

// Connection URL
var url = 'mongodb://localhost:27017/database';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  if(err) throw err;    
  console.log("Connected successfully to server");
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

npm install mongoose --save
// Include Mongoose using Node.js
const mongoose = require('mongoose');
// Include Mongoose using ES6
import mongoose from 'mongoose';

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
  console.log("Connected to DB");
  //do operations which involve interacting with DB.

Full Stack Tutorials

Author @FullStackTutorials | View all Articles