Leverage Turing Intelligence capabilities to integrate AI into your operations, enhance automation, and optimize cloud migration for scalable impact.
Advance foundation model research and improve LLM reasoning, coding, and multimodal capabilities with Turing AGI Advancement.
Access a global network of elite AI professionals through Turing Jobs—vetted experts ready to accelerate your AI initiatives.
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.
Let’s create a small CRUD API for a simple feature to understand how to work on MongoDB to store data.
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) { } })
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.
const mongooseLib = require('mongoose')
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) } } }
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 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.
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.
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.
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.
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.
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.