DEV Community

opeyemi mathew adewumi
opeyemi mathew adewumi

Posted on

Setting up MongoDB using Mongoose in Node.js

How to Set up MongoDB using Mongoose in Node.js

MongoDB is a popular NoSQL database that allows for flexible and efficient data storage. Mongoose is a popular ODM (Object Data Modeling) library for MongoDB that makes it easy to interact with the database from Node.js applications. In this article, we will go through the steps to set up MongoDB using Mongoose in Node.js.

Step 1: Install MongoDB

First, we need to have MongoDB installed on our machine. You can download the Community Server edition from the official MongoDB website if you don't have one yet. Follow the installation instructions for your operating system.

Step 2: Install Mongoose

Once you have successfully install MongoDB, you need to install Mongoose in your Node.js project. You can do this using npm by running the following command in your terminal:

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

Step 3: Establish a Connection

Next, we have to create a new JavaScript file and require Mongoose:

const mongoose = require('mongoose');
Enter fullscreen mode Exit fullscreen mode

Then, use the mongoose.connect() method to connect to your MongoDB database:

mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
Enter fullscreen mode Exit fullscreen mode

Replace 'mongodb://localhost/mydatabase' with the connection string to your MongoDB database.

Step 4: Define a Data Structure

After connecting to database, define a schema for your data using the mongoose.Schema object:

const userSchema = new mongoose.Schema({
  name: String,
  email: String
});
Enter fullscreen mode Exit fullscreen mode

Step 5: Create a Model

Once you have defined a schema, you can create a model using the mongoose.model() method:

const User = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

Step 6: Use the Model

Finally, you can use the model to interact with your database. For example, you can create a new user document using the create() method:

const user = new User({ name: 'John Doe', email: 'johndoe@example.com' });
user.save();
Enter fullscreen mode Exit fullscreen mode

This creates a new user document in your database.
By following these steps, you'll be up and running with MongoDB and Mongoose in Node.js, ready to build powerful and scalable applications.

Top comments (0)