FOR DEVELOPERS

How to Connect Node.js to MongoDB

How to Connect Node.js to MongoDB

Node.js is a framework used to build servers, while MondoDB is a schemaless documented structural database that can store data in JSON format. Compared to some other databases, MongoDB is fast and scalable. It is also flexible owing to the non-relational schema structure. This article will illustrate how to connect Node.js to MongoDB to store data.

Creating a CRUD API in Node.js

Let’s create a small CRUD API for a simple feature to understand how to work on MongoDB to store data.

  • Create user
  • Update user
  • Delete user.

Node.js application setup

  1. Create an empty folder and open it in any IDE.
  2. Run the command “npm init” for basic configuration.
  3. Run the command “npm install express body-parser”.
app.use(express.urlencoded({ extended: true }));

Note: Express.js is a Node.js framework that works as middleware to create APIs and other actions.

const express = require("express");
const bodyParser = require('body-parser')

const app = express(); app.use(express.urlencoded({ extended: true }))

app.listen(Port, () => console.log("server is running on port", Port) );

Here, CRUD API actions Create/Get/Update/Delete have been created.

app.get("/", async (req, res) => {
Try {
res.status(200).send(“get all data”)
}
catch(error) {
}
})

  • Create record API app.post("/", async (req, res) => { Try { res.status(200).send(“get all data”) } catch(error) { } })

  • Update record API app.put("/", async (req, res) => { Try { res.status(200).send(“get all data”) } catch(error) { } })

  • Delete record API app.deletet("/", async (req, res) => { Try { res.status(200).send(“get all data”) } catch(error) { } })

Connecting MongoDB to Node.js with Mongoose

Mongoose is a library provided by NPM (Node Package Manager) for the MongoDB database. With it, you can define collection schema, relationships between collections, database query builders, lookups, aggregation pipelines, etc.

  1. Run the command “npm install mongoose” to install the library in Node.js.
const mongooseLib = require('mongoose')
  • Connect to remote MongoDB Atlas

module.exports = { MongoDBConnection: async () => { try { await mongooseLib.connect('mongodb+srv://<username>:<password>@cluster0.c8nbwsh.mongod b.net/?retryWrites=true&w=majority'); console.log("database connect") } catch (error) { console.log(error) } } }

  • Connect to local mongodb database

module.exports = { MongoDBConnection: async () => { try { await mongooseLib.connect('mongodb://127.0.0.1:27017/test'); console.log("database connect") } catch (error) { console.log(error) } } }

Next, create a function and define a variable with any name from the Mongoose library like what has been defined in the above image “mongooseLib”. Then, call a connect method from the Mongoose library. The method requires at least one param to connect MongoDB to the Node.js server.

  • To connect your local Node.js server application to MongoDB, you need to set up MongoDB in your system and pass the MongoDB IP with the database name in the connect method.
  • For hosted MongoDB, you need to create an account on MongoDB Atlas. Once you configure the setup for the database, get the query string from MongoDB Atlas and pass it in the connect method.

Mongoose in Node.js

To create each document in a collection, you need to first create a schema for any collection in MongoDB.

Here’s a schema for the user collection.

- Create a variable for userModel by require from mongoose library
const mongooseUser = require('mongoose')
  • Create a mongoose schema with some properties const userSchema = new mongooseUser.Schema({ fullName: {

  • FullName property will be type of String type: String },

    email: {

  • Email will be unique as we define the property with unique keyword true unique: true type: String }, userName: { type: String }, password: { type: String, }, }, { timestamps: true })

  • Create a model for a defined schema so that we can perform different queries/operations on User collection. const Users = mongooseUser.model('user', userSchema)

After defining the schema, use the model method or Mongoose library to create the schema so that you can perform queries and related actions on the user collection.

Create user

app.post("/", async (req, res) => {
	try {
           // eg.      {
           // fullName: “jon den”,
           // email: “jon@gmail.com”,
          //  password: “ 23234fsf4t3grthyj56uerth”
          //   }

              const createUser = await Users.create({...req.body});

              res.status(200).send(“get all data”)
               }
           catch(error) {
                res.status(400).send(error)
               }
})

Process to create a new document in the user collection: in the POST API, use the create method from the user schema instance and pass the body that you get in req.body from the API. The method requires a JSON object with keys-values that are defined in the user schema.

Update user

app.put("/", async (req, res) => {
try {
          const updatedUser = await User.findOneAndUpdate(                      { _id: mongoose.Types.ObjectId(req.body.userId) },
                      { …req.body},
                      { returnDocument: 'after' }
                      )
              res.status(200).send(“data updated”)
               }
           catch(error) {
                res.status(400).send(error)
               }
})

To update any record in the user collection, use the findOneAndUpdate method. It requires the document ID which you get from req.body. Then, pass it as an object.

Notice that the ID has been passed in mongoose.Types.ObjectId. This is because any document in MongoDB collected by default is the ObjectId type. So, to match the ID type, you use the mongoose.Types.ObjectId method. The second param requires updated data to replace the old one, while the third param is to return the new updated record.

Delete user

app.delete("/", async (req, res) => {
	try {

          const updatedUser = await User.findOneAndDelete(
                      { _id: mongoose.Types.ObjectId(req.body.userId) }
)
              res.status(200).send(“get all data”)
               }
           catch(error) {
                res.status(400).send(error)
               }
})

Use the findOneAndDelete method to delete any document from the user collection. The method receives a single required param, which is the document ID. The method will first find the record by ID and delete it from the collection.

Mongoose library has all the query methods that support MongoDB operations. You can find different actions like lookups, aggregation, pipeline, indexing, etc.

Conclusion

We’ve discussed how to connect MongoDB in Node.js using the Mongoose library. We learned about connectivity from the localhost MongoDB database and from MongoDB Atlas. We also learned to create basic CRUD APIs in Node.js, create a schema for collection, and perform basic CRUD queries using Mongoose. Seeing as MongoDB is a complete database and widely used, it’s important to know how to work with it.

Author

  • How to Connect Node.js to MongoDB

    Zain Ahmed

    Zain Ahmed is a Software Engineer and content creator/writer, He loves to take challenges and explore new Tech stuff. He has a vision to contribute knowledge to the challenges and explore new Tech stuff. He has a vision to contribute knowledge to the community from where he learned in his initial career.

Frequently Asked Questions

MongoDB Atlas is a cloud-hosted database-as-a-service where you can host your MongoDB database. It offers a free plan for basic space.

Yes, you can add as many databases as you want in a single Node.js server application.

MongoDB is a non-relational document database that provides support for JSON-like storage. You can create relations between different collections with their IDs.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.