In Chapter S2 06: Database, Schema, Models & Mongoose the signup route saved a hardcoded user. Now you'll build real, dynamic APIs: create a user from the request body, find users, delete them and update them, the full CRUD set from Chapter 13: Creating a database & mongodb, this time with Express and Mongoose. You'll also learn the most common bugs and security holes in these APIs, and how to avoid them.
In this chapter you'll learn
- the difference between a JavaScript object and JSON
- how
express.json()turns a request body intoreq.body - a dynamic signup API, plus APIs to get, list, delete and update users
find,findOne,findById,findByIdAndDelete,findByIdAndUpdateand their options- mass assignment and NoSQL injection, and how to prevent them
Before you start: read Chapter S2 04: Routing and Request handlers (req.params, req.query, req.body) and Chapter S2 06: Database, Schema, Models & Mongoose (models).
JavaScript objects vs JSON
They look almost the same, which confuses many beginners:
// a JavaScript object: lives in memory, part of your code
const user = { firstName: "Akshay", age: 22, greet() { return "hi"; } };
// JSON: TEXT that follows strict rules, used to send data between programs
const json = '{"firstName":"Akshay","age":22}';// a JavaScript object: lives in memory, part of your code
const user = { firstName: "Akshay", age: 22, greet() { return "hi"; } };
// JSON: TEXT that follows strict rules, used to send data between programs
const json = '{"firstName":"Akshay","age":22}';| JavaScript object | JSON | |
|---|---|---|
| What it is | a value in memory | a string (text format) |
| Keys | quotes optional | must use double quotes |
| Values | anything: functions, undefined, Date, ... | only strings, numbers, booleans, null, arrays, objects |
| Used for | working with data in code | sending data over the network or saving to files |
| Convert | JSON.stringify(obj) → JSON | JSON.parse(json) → object |
When Postman sends {"firstName":"Akshay"}, it arrives at your server as text. Something has to parse it into a JavaScript object.
express.json()
That something is Express's built-in middleware (Chapter S2 05: Middlewares and Error Handlers):
app.use(express.json()); // register once, BEFORE the routesapp.use(express.json()); // register once, BEFORE the routesFor every request with a Content-Type: application/json header, it reads the body, runs JSON.parse, and puts the result in req.body. Without it, req.body is undefined.
Create: a dynamic signup API
app.post("/signup", async (req, res) => {
const user = new User(req.body); // build the document from the request
try {
await user.save();
res.status(201).send("User added successfully");
} catch (err) {
res.status(400).send("Error saving the user: " + err.message);
}
});app.post("/signup", async (req, res) => {
const user = new User(req.body); // build the document from the request
try {
await user.save();
res.status(201).send("User added successfully");
} catch (err) {
res.status(400).send("Error saving the user: " + err.message);
}
});Send this from Postman (Body → raw → JSON):
{
"firstName": "Virat",
"lastName": "Kohli",
"emailId": "virat@kohli.com",
"password": "Virat@123",
"age": 35
}{
"firstName": "Virat",
"lastName": "Kohli",
"emailId": "virat@kohli.com",
"password": "Virat@123",
"age": 35
}It works, but new User(req.body) has a security problem, explained next.
Mass assignment: never trust req.body blindly
new User(req.body) copies whatever the client sends into the document. Mongoose's strict mode (on by default) drops fields that aren't in the schema, which helps. But any field that is in the schema can be set by the client, even ones they shouldn't control, such as a future isAdmin or isPremium flag. This is called mass assignment.
Pick the allowed fields explicitly:
app.post("/signup", async (req, res) => {
const { firstName, lastName, emailId, password } = req.body; // only these
const user = new User({ firstName, lastName, emailId, password });
// ...save as before
});app.post("/signup", async (req, res) => {
const { firstName, lastName, emailId, password } = req.body; // only these
const user = new User({ firstName, lastName, emailId, password });
// ...save as before
});In Chapter S2 08: Data Sanitization & Schema Validations you'll add validation and in Chapter S2 09: Encrypting Passwords password hashing to this route.
Read: getting users
All users: find
// Feed API: GET /feed → all users
app.get("/feed", async (req, res) => {
try {
const users = await User.find({}); // {} = no filter = everyone
res.send(users);
} catch (err) {
res.status(500).send("Something went wrong");
}
});// Feed API: GET /feed → all users
app.get("/feed", async (req, res) => {
try {
const users = await User.find({}); // {} = no filter = everyone
res.send(users);
} catch (err) {
res.status(500).send("Something went wrong");
}
});find always returns an array: [] if nothing matches. (The real feed, with filtering and pagination, comes in Chapter S2 14: Building Feed API and Pagination.)
One user by email: findOne
The course version reads the email from the body of a GET request and checks users.length. Both are problems, so here's a fixed version first, then the explanation:
// GET /user?emailId=virat@kohli.com
app.get("/user", async (req, res) => {
try {
const user = await User.findOne({ emailId: req.query.emailId });
if (!user) {
return res.status(404).send("User not found");
}
res.send(user);
} catch (err) {
res.status(500).send("Something went wrong");
}
});// GET /user?emailId=virat@kohli.com
app.get("/user", async (req, res) => {
try {
const user = await User.findOne({ emailId: req.query.emailId });
if (!user) {
return res.status(404).send("User not found");
}
res.send(user);
} catch (err) {
res.status(500).send("Something went wrong");
}
});findOnereturns one document ornull, never an array. Checkinguser.length === 0doesn't work: for a found user,.lengthisundefined; for a missing user,null.lengththrowsTypeError, so the client gets "Something went wrong" instead of "User not found". Checkif (!user)instead.- Use the query string for GET. A body on a GET request is discouraged, and many clients and proxies drop it. Put lookups in
req.query(orreq.params).
If two documents had the same email, findOne returns one of them; without .sort(), MongoDB doesn't promise which. The real fix is to make duplicates impossible with a unique email (Chapter S2 08: Data Sanitization & Schema Validations).
One user by ID: findById
// GET /user/6702a1f4c3e9b8a1d2f4e5a6
app.get("/user/:userId", async (req, res) => {
const user = await User.findById(req.params.userId); // shortcut for findOne({ _id: ... })
if (!user) return res.status(404).send("User not found");
res.send(user);
});// GET /user/6702a1f4c3e9b8a1d2f4e5a6
app.get("/user/:userId", async (req, res) => {
const user = await User.findById(req.params.userId); // shortcut for findOne({ _id: ... })
if (!user) return res.status(404).send("User not found");
res.send(user);
});Mongoose converts the string ID into an ObjectId for you. An invalid ID string (like "abc") makes the query throw a CastError, so wrap it in try/catch (or rely on the error handler in Express 5: Chapter S2 05: Middlewares and Error Handlers).
Delete: findByIdAndDelete
// DELETE /user/6702a1f4c3e9b8a1d2f4e5a6
app.delete("/user/:userId", async (req, res) => {
try {
const deleted = await User.findByIdAndDelete(req.params.userId);
if (!deleted) return res.status(404).send("User not found");
res.send("User deleted successfully");
} catch (err) {
res.status(400).send("Something went wrong");
}
});// DELETE /user/6702a1f4c3e9b8a1d2f4e5a6
app.delete("/user/:userId", async (req, res) => {
try {
const deleted = await User.findByIdAndDelete(req.params.userId);
if (!deleted) return res.status(404).send("User not found");
res.send("User deleted successfully");
} catch (err) {
res.status(400).send("Something went wrong");
}
});findByIdAndDelete returns the deleted document, or null if nothing matched. Check it, so you don't report success for a user that never existed. (The course sends the ID in the body; putting it in the URL is the REST way, and DELETE bodies have the same problem as GET bodies.)
Update: findByIdAndUpdate
// PATCH /user/6702a1f4c3e9b8a1d2f4e5a6 body: { "age": 36, "about": "Cricketer" }
app.patch("/user/:userId", async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.userId, req.body, {
returnDocument: "after", // return the UPDATED document (default is "before")
runValidators: true, // apply schema validation to the update
});
if (!user) return res.status(404).send("User not found");
res.send(user);
} catch (err) {
res.status(400).send("Update failed: " + err.message);
}
});// PATCH /user/6702a1f4c3e9b8a1d2f4e5a6 body: { "age": 36, "about": "Cricketer" }
app.patch("/user/:userId", async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.userId, req.body, {
returnDocument: "after", // return the UPDATED document (default is "before")
runValidators: true, // apply schema validation to the update
});
if (!user) return res.status(404).send("User not found");
res.send(user);
} catch (err) {
res.status(400).send("Update failed: " + err.message);
}
});The options matter more than they look:
| Option | Default | Why you want it |
|---|---|---|
returnDocument: "after" (or new: true) | "before": you get the old document | so the response shows the data as it is now |
runValidators: true | false: schema validators are skipped for updates | otherwise invalid data goes straight into the database (Chapter S2 08: Data Sanitization & Schema Validations) |
Also note:
- Mongoose wraps the update in
$setfor you, so only the fields you send change. That's PATCH behaviour (Chapter S2 02: Features, HLD LLD and Planning). - The first argument is the ID itself:
findByIdAndUpdate(userId, ...). Passing{ _id: userId }happens to work too, but it isn't the intended form. - This route still lets a client update any field, including
emailIdorpassword. Chapter S2 08: Data Sanitization & Schema Validations adds a list of allowed fields.
PATCH vs PUT for this API
| PATCH | PUT | |
|---|---|---|
| Body contains | only the fields to change | the complete document |
| Missing fields | stay as they are | are removed |
| Mongoose equivalent | findByIdAndUpdate (with $set) | findOneAndReplace / replaceOne |
NoSQL injection
There's no SQL here, but MongoDB has its own injection problem. Look at this login lookup:
const user = await User.findOne({ emailId: req.body.emailId });const user = await User.findOne({ emailId: req.body.emailId });If a client sends an object instead of a string:
{ "emailId": { "$ne": null } }{ "emailId": { "$ne": null } }the query becomes { emailId: { $ne: null } }: "any user whose email is not null", which matches the first user in the database. Combined with a weak password check, that's an account takeover.
Defences:
- Validate types: make sure
emailIdis a string (and a valid email) before querying. The validation helpers in Chapter S2 08: Data Sanitization & Schema Validations and Chapter S2 09: Encrypting Passwords do this. - Turn on Mongoose's filter sanitizing once, at startup:
mongoose.set("sanitizeFilter", true);mongoose.set("sanitizeFilter", true);It wraps any object containing operators in $eq, so { "$ne": null } is compared as a literal value and matches nothing. (We checked this on Mongoose 9: the filter becomes { emailId: { $eq: { $ne: null } } }.)
Common mistakes
- No
express.json():req.bodyisundefined. - Treating
findOne's result as an array:null.lengthcrashes. - Forgetting
runValidators: trueon updates: bad data gets saved. - Not checking for
nullafterfindById...: reporting success for something that doesn't exist. new User(req.body)with sensitive fields in the schema: mass assignment.- Passing
req.bodyvalues straight into filters: NoSQL injection.
Key takeaways
- JSON is text; a JavaScript object is a value in memory.
express.json()parses JSON bodies intoreq.body. find()returns an array;findOne()andfindById()return a document ornull.findByIdAndDelete/findByIdAndUpdatereturnnullwhen nothing matched: send a 404.- For updates, use
returnDocument: "after"andrunValidators: true. - Pick allowed fields explicitly (mass assignment) and validate input types (NoSQL injection);
mongoose.set("sanitizeFilter", true)adds a safety net. - Use query strings or params for GET/DELETE inputs, not bodies.
Interview questions
Q1. What is the difference between JSON and a JavaScript object?
A JavaScript object is an in-memory data structure; it can contain functions, undefined, dates and so on, and keys don't need quotes. JSON is a text format for exchanging data: keys must be double-quoted, and values are limited to strings, numbers, booleans, null, arrays and objects. JSON.stringify converts an object to JSON, and JSON.parse converts JSON back to an object.
Q2. What does express.json() do?
It's built-in body-parsing middleware. For requests with Content-Type: application/json, it reads the raw body, parses it with JSON.parse, and stores the result in req.body. It must be registered before the routes that need it. It also limits body size (100 KB by default), which protects against huge payloads.
Q3. What's the difference between find, findOne and findById?
find(filter) returns an array of all matching documents (empty if none). findOne(filter) returns the first matching document or null. findById(id) is shorthand for findOne({ _id: id }), with the string cast to an ObjectId; an invalid ID throws a CastError.
Q4. Do Mongoose validators run on findByIdAndUpdate?
Not by default. Validators run on save() and create(). For query updates (updateOne, findOneAndUpdate, findByIdAndUpdate), you must pass { runValidators: true }. Even then, update validators only check the fields in the update, and inside them this isn't the document.
Q5. What is NoSQL injection, and how do you prevent it?
It's when user input that should be a plain value is an object with query operators, changing the query's meaning. For example {"emailId": {"$ne": null}} turns "find this email" into "find any user". Prevent it by validating input types (ensure strings are strings), using a validation library, and enabling mongoose.set('sanitizeFilter', true), or mongoose.trusted() for filters you build yourself.
Q6. What is mass assignment?
A vulnerability where the server copies all request fields into a database model (new User(req.body) or an update with req.body), letting attackers set fields they shouldn't control, like a role or a verified flag. The fix is an allow-list: copy only the specific fields each endpoint should accept.
Q7. What does { new: true } / { returnDocument: "after" } do in findOneAndUpdate?
By default, findOneAndUpdate and findByIdAndUpdate return the document as it was before the update. { new: true } (Mongoose's name) or { returnDocument: "after" } (the driver's name) returns the updated document instead.
What's next
Right now, anyone can sign up with an empty name, an age of 3 or the email "banana". In Chapter S2 08: Data Sanitization & Schema Validations you'll add validation at the schema level and the API level so only clean data reaches the database.