Creating a CRUD API in Node.js
To learn how to work with MongoDB, let’s create a CRUD API for a simple feature.
- Create user
- Update user
- Delete user.
Node.js application setup
- Create an empty folder and open it in any IDE.
- Run the command “npm init” for basic configuration.
- 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 like a toolbox for Node.js developers who work with MongoDB databases. It is a package that you can get from NPM (Node Package Manager) that helps you do many things with your database, such as changing the structure of your data, organizing it, combining different types of data into one. To group together. Joining, performing complex searches, and combining data in useful ways. Basically, it makes the MongoDB database easier to manage and use, so you can focus more on creating great content with your data.
- 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)
}
}
}
After outlining the blueprint for your data structure, use either the model method or the Mongoose library to create the schema. This step allows you to easily perform queries and other relevant actions on the Users collection stored in your database.
- To link your local Node.js server to MongoDB, you first need to install MongoDB on your computer. Then, when you connect your server to MongoDB, you give it the IP address where MongoDB resides and the name of the database you want to connect to.
- If you use MongoDB Atlas, a hosted MongoDB service, you start by signing up for an account there. Once you set up your database on MongoDB Atlas, they will give you a special connection string. You simply copy that string and paste it into your Node.js code to connect your server to your MongoDB Atlas database.
Mongoose in Node.js
MongoDB requires you to create a schema before you can create any document in a collection.
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 outlining the structure of your data (schema), use either the model method or the Mongoose library to set up the schema. This enables you to easily search and manipulate data in user collections.
Create user
app.post("/", async (req, res) => {
try {
// eg. {
// fullName: “jon den”,
// email: “[email protected]”,
// password: “ 23234fsf4t3grthyj56uerth”
// }
const createUser = await Users.create({...req.body});
res.status(200).send(“get all data”)
}
catch(error) {
res.status(400).send(error)
}
})
To add a new user to the collection, you will use the POST API. Inside this API, you will use the “Create” method of the user schema. For this method you need data obtained from req.body
. Make sure this data is structured as a JSON object with keys and values matching the user schema. This ensures that the new user document is correctly formatted and stored in the database.
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 a record in the Users collection, you would use the findOneAndUpdate
method. This method requires the ID of the document you want to update, which usually comes from req.body
.
Now, IDs in MongoDB collections are of type ObjectID by default. So, to match the ID type, you use the mongoose.Types.ObjectId
method.
When you call findOneAndUpdate
, the first thing you provide is an object that specifies the document you want to update based on its ID. Then, you pass updated data that will replace the old information in the document. Finally, if you set the third parameter to true, the method will return the new updated record. This ensures that the ID types match correctly and that the old data is seamlessly replaced with the new data.
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)
}
})
To delete a document from a user collection you can use the findOneAndDelete
method in Mongoose. This method requires only one thing: the ID of the document you want to delete. It works by first finding the document with that ID and then removing it from the collection.
Mongoose provides a wide range of query methods for working with MongoDB, including tasks such as searching, aggregating data, using pipelines, setting indexes, and more. These tools make it easy for developers to effectively manage and access data in their applications.