Establishing a connection between Node.js and MongoDB with Mongoose: A guide to connecting to a MongoDB database using Node.js

Posted by


In this tutorial, we will learn how to connect Node.js with MongoDB using Mongoose, a popular Node.js library that provides a powerful and expressive way to interact with MongoDB databases. Mongoose simplifies the process of creating and interacting with MongoDB databases by providing a schema-based solution for modeling your data.

Before we get started, make sure you have Node.js and MongoDB installed on your machine. If you haven’t already installed them, you can find detailed instructions on the official Node.js and MongoDB websites.

Step 1: Install Mongoose

First, we need to install Mongoose in our Node.js project. Open your terminal or command prompt and run the following command:

npm install mongoose

This will install Mongoose as a dependency in your project.

Step 2: Create a MongoDB Database

Next, let’s create a MongoDB database where we will store our data. Open your MongoDB shell or use a GUI tool like MongoDB Compass to create a new database. You can use the following command in the MongoDB shell to create a new database:

use mydatabase

Replace mydatabase with the name of your database.

Step 3: Create a Node.js Project

Now, let’s create a new Node.js project for our application. Create a new directory for your project and navigate to it in your terminal or command prompt. Run the following command to initialize a new Node.js project:

npm init -y

This will create a package.json file in your project directory.

Step 4: Create a connection to MongoDB using Mongoose

Create a new JavaScript file in your project directory and import Mongoose at the top of the file:

const mongoose = require('mongoose');

Next, establish a connection to your MongoDB database using Mongoose. You can use the mongoose.connect() method to connect to your MongoDB database. Add the following code to connect to your database:

mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to MongoDB');
  })
  .catch((error) => {
    console.error('Error connecting to MongoDB', error);
  });

Replace mongodb://localhost/mydatabase with the connection URL to your MongoDB database. This URL consists of the MongoDB server (localhost in this case) and the name of your database (mydatabase in this case).

Step 5: Define a Schema and Model

Now that we have connected to our MongoDB database, let’s define a schema for our data and create a model using Mongoose. In the same JavaScript file, add the following code to define a schema and create a model:

const { Schema } = mongoose;

const userSchema = new Schema({
  name: String,
  email: String,
  age: Number,
});

const User = mongoose.model('User', userSchema);

In this code, we are creating a schema with three fields: name, email, and age. We then create a model named User using this schema.

Step 6: Insert Data into MongoDB

Now that we have a model for our data, let’s insert some data into our MongoDB database. Add the following code to insert a new user into the database:

const newUser = new User({
  name: 'John Doe',
  email: 'johndoe@example.com',
  age: 30,
});

newUser.save()
  .then(() => {
    console.log('User saved to database');
  })
  .catch((error) => {
    console.error('Error saving user to database', error);
  });

This code creates a new instance of the User model with the specified data and saves it to the database using the save() method.

Step 7: Query Data from MongoDB

Finally, let’s query data from our MongoDB database using Mongoose. Add the following code to query all users from the database:

User.find()
  .then((users) => {
    console.log('All users:', users);
  })
  .catch((error) => {
    console.error('Error querying users from database', error);
  });

This code uses the find() method to retrieve all users from the database and logs them to the console.

Step 8: Run your Node.js application

Save your changes to the JavaScript file and run your Node.js application using the following command:

node app.js

Replace app.js with the name of your JavaScript file.

If everything is set up correctly, you should see the output in the console indicating that your application has connected to MongoDB, inserted a new user, and queried all users from the database.

Congratulations! You have successfully connected Node.js with MongoDB using Mongoose. You can now use Mongoose to interact with your MongoDB database in your Node.js applications. Feel free to explore more features of Mongoose and MongoDB to build powerful and efficient applications.

0 0 votes
Article Rating
30 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@BhartiSingh-ns6hj
2 months ago

Ty bro

@catharinnivitha7587
2 months ago

Thanks a lot for the video! I was stuck in it for a long time

@mrdoubleS
2 months ago

help with cloud

@rishidongre6772
2 months ago

Thanx brother

@heshamelmesalmy5950
2 months ago

please help : error
SyntaxError: Unexpected token '.'

←[90m at Object.compileFunction (vm.js:344:18)←[39m

←[90m at wrapSafe (internal/modules/cjs/loader.js:1048:15)←[39m

←[90m at Module._compile (internal/modules/cjs/loader.js:1082:27)←[39m

←[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1138:10)←[39m

←[90m at Module.load (internal/modules/cjs/loader.js:982:32)←[39m

←[90m at Function.Module._load (internal/modules/cjs/loader.js:875:14)←[39m

←[90m at Module.require (internal/modules/cjs/loader.js:1022:19)←[39m

←[90m at require (internal/modules/cjs/helpers.js:72:18)←[39m

at Object.<anonymous> (D:ProgrammingNode JScodeservernode_modules←[4mmongodb←[24mlibindex.js:6:17)

←[90m at Module._compile (internal/modules/cjs/loader.js:1118:30)←[39m

PS D:ProgrammingNode JScodeserver>

this is my steps :
const express = require('express')

const mongoose = require('mongoose')

const app = express()

mongoose.connect('mongodb://localhost:27017')

const UserSchema = new mongoose.Schema ({

name: String,

age: Number

})

const UserModel = mongoose.model("user", UserSchema)

app.get("/", (req, res) => {

UserModel.find({}).then(function(users) {

res.json(users)

}).catch(function(err) {

console.log(err)

})

})

app.listen(3000, () => {

console.log("server is running")

})

@jillasquad8940
2 months ago

Bro during run the server collection name I put "ball" then I go to check mongo db data base it will create "ball" and also "balls" additional create collection but I run ball it's not running after balls collection running why this collection puts end 's' like balls users

@Manoj_Gowda89
2 months ago

Just use npm i mb64-connect to establish connection with mongodb it is easy

@louaibouraoui2469
2 months ago

nice man

@manojkasal147
2 months ago

Thanks mannn

@amritharavikumar9760
2 months ago

How to connect mongoDB with cypress?

@soulfulhuman8724
2 months ago

Please reply :-
Its working fine.
I have a doubt, why is it so that we are getting id in response.
How is schema helping then? 😅

@shah87874
2 months ago

thnx a lot bro…..god bless u

@Elizabeth_Calmau
2 months ago

Wow, that was super helpful. I appreciate it so much

@krishnusingh7223
2 months ago

Not working

@SearchAndSolve12345
2 months ago

Weldon bro
success connection ❤❤❤❤

@karangavade774
2 months ago

Bro I'm getting referenceerror: users js not defined…

@orangesecurity3908
2 months ago

Большое спасибо!!! Очень помогли ❤

@TonyStark-ir4om
2 months ago

good video but please explain with each line what and why are you writing that piece of code for starters its very unclear what's happening

@jetlinkarkha9659
2 months ago

When I run I got syntax error said option.? session so what should I do. I am using nodejs version 12 and mongodb 7.0

@ghislainondeno1215
2 months ago

every time I try to launch the server I always get this error and yet mongodb is launched correctly

PS D:angular1mongotestserver> node index.js

Server is running

D:angular1mongotestservernode_modulesmongooselibconnection.js:809

err = new ServerSelectionError();

^

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017

at _handleConnectionErrors (D:angular1mongotestservernode_modulesmongooselibconnection.js:809:11)

at NativeConnection.openUri (D:angular1mongotestservernode_modulesmongooselibconnection.js:784:11) {

reason: TopologyDescription {

type: 'Unknown',

servers: Map(1) {

'localhost:27017' => ServerDescription {

address: 'localhost:27017',

type: 'Unknown',

hosts: [],

passives: [],

arbiters: [],

tags: {},

minWireVersion: 0,

maxWireVersion: 0,

roundTripTime: -1,

lastUpdateTime: 608858250,

lastWriteDate: 0,

error: MongoNetworkError: connect ECONNREFUSED ::1:27017

at connectionFailureError (D:angular1mongotestservernode_modulesmongodblibcmapconnect.js:379:20)

at Socket.<anonymous> (D:angular1mongotestservernode_modulesmongodblibcmapconnect.js:285:22)

at Object.onceWrapper (node:events:632:26)

at Socket.emit (node:events:517:28)

at emitErrorNT (node:internal/streams/destroy:151:8)

at emitErrorCloseNT (node:internal/streams/destroy:116:3)

at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {

[Symbol(errorLabels)]: Set(1) { 'ResetPool' },

[cause]: Error: connect ECONNREFUSED ::1:27017

at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1555:16) {

errno: -4078,

code: 'ECONNREFUSED',

syscall: 'connect',

address: '::1',

port: 27017

}

},

topologyVersion: null,

setName: null,

setVersion: null,

electionId: null,

logicalSessionTimeoutMinutes: null,

primary: null,

me: null,

'$clusterTime': null

}

},

stale: false,

compatible: true,

heartbeatFrequencyMS: 10000,

localThresholdMS: 15,

setName: null,

maxElectionId: null,

maxSetVersion: null,

commonWireVersion: 0,

logicalSessionTimeoutMinutes: null

},

code: undefined

}

Node.js v18.18.0