Database CRUD operations with async/await
Using Mongoose, we can build REST controller endpoints inside our Express app to perform standard CRUD operations against a MongoDB database.
1 REST Endpoint Controller Actions
Ensure you handle asynchronous operations cleanly using async/await syntax and try/catch blocks:
JavaScript — controllers/userController.js
const User = require("../models/User");
// Create user
app.post("/users", async (req, res) => {
try {
const newUser = new User(req.body);
await newUser.save();
res.status(201).json(newUser);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// Read user profiles
app.get("/users", async (req, res) => {
try {
const users = await User.find();
res.status(200).json(users);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
2 Modifying and Deleting Records
JavaScript — Update & Delete Actions
// Update database record by ID
app.put("/users/:id", async (req, res) => {
try {
const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(updatedUser);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// Delete database record by ID
app.delete("/users/:id", async (req, res) => {
try {
await User.findByIdAndDelete(req.params.id);
res.json({ message: "User deleted successfully" });
} catch (err) {
res.status(400).json({ error: err.message });
}
});
3 Code Challenge
Challenge: Write a route mapping GET requests to
/users/:username. Lookup the database for a user matching the passed username param, returning a 404 error if not found.