Connection requests can be sent (Chapter S2 12: Logical DB Query and Compound Indexes). Now the receiver needs to review them, and see who sent them. In this chapter you'll build three APIs, and the most important skill in this course: thinking an API through before writing it. You'll also learn ref and populate, Mongoose's way of joining data from two collections.
In this chapter you'll learn
- a step-by-step method for designing an API: who's calling, what may they do, which edge cases exist
- the review request API: accept or reject, with ownership checks
refandpopulate: turning stored IDs into user details- the requests received API and the connections API
- returning only safe fields, and avoiding the N+1 query problem
Before you start: read Chapter S2 12: Logical DB Query and Compound Indexes (the ConnectionRequest model and statuses).
How to think through an API
Before writing any route, answer these questions in order:
- Who is calling? Which user is logged in? (Always from
req.user, never from the request body.) - What are the inputs? Which params, query values and body fields, and which values are allowed?
- What must be true for this action to be allowed? (Ownership, current state, existence.)
- What does the database query look like, so that it enforces those rules?
- What does each outcome return? The success response, and a status code for each failure.
The review API is a perfect example.
The review request API
Endpoint: POST /request/review/:status/:requestId, where status is accepted or rejected.
Let's apply the method. User B wants to accept a request that A sent:
- Who's calling? B, from
req.user. - Inputs:
statusmust beacceptedorrejected(a receiver can't setinterested).requestIdmust be a valid ID. - What must be true?
- the request exists
- it was sent to B: A must not be able to accept their own request, and nobody else may touch it
- it's still
interested: anignoredrequest was never sent to B, and an already-reviewed request can't be reviewed again
- Query: all three conditions fit into one
findOne:{ _id: requestId, toUserId: B, status: "interested" } - Outcomes: found → update status,
200; not found →404; bad status →400.
// src/routes/request.js
requestRouter.post("/request/review/:status/:requestId", userAuth, async (req, res) => {
try {
const loggedInUser = req.user;
const { status, requestId } = req.params;
// 2. only these two statuses can be set by the RECEIVER
const allowedStatus = ["accepted", "rejected"];
if (!allowedStatus.includes(status)) {
return res.status(400).json({ message: "Status not allowed: " + status });
}
// 3 + 4. one query checks existence, ownership and current state
const connectionRequest = await ConnectionRequest.findOne({
_id: requestId,
toUserId: loggedInUser._id,
status: "interested",
});
if (!connectionRequest) {
return res.status(404).json({ message: "Connection request not found" });
}
// 5. update and respond
connectionRequest.status = status;
const data = await connectionRequest.save();
res.json({ message: "Connection request " + status, data });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});// src/routes/request.js
requestRouter.post("/request/review/:status/:requestId", userAuth, async (req, res) => {
try {
const loggedInUser = req.user;
const { status, requestId } = req.params;
// 2. only these two statuses can be set by the RECEIVER
const allowedStatus = ["accepted", "rejected"];
if (!allowedStatus.includes(status)) {
return res.status(400).json({ message: "Status not allowed: " + status });
}
// 3 + 4. one query checks existence, ownership and current state
const connectionRequest = await ConnectionRequest.findOne({
_id: requestId,
toUserId: loggedInUser._id,
status: "interested",
});
if (!connectionRequest) {
return res.status(404).json({ message: "Connection request not found" });
}
// 5. update and respond
connectionRequest.status = status;
const data = await connectionRequest.save();
res.json({ message: "Connection request " + status, data });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});The status in the query must be spelled exactly like the schema's enum: "interested". The original course notes misspell it here as "intrested". Since no document has that value, the query would find nothing and every review would return 404. One shared spelling, everywhere (Chapter S2 11: Diving into the APIs and Express router).
Why one combined query instead of findById followed by if checks? It's fewer lines, it's one round trip, and the response doesn't reveal which check failed. "Not found" is the same whether the ID is wrong or the request belongs to someone else, so nobody can probe other people's request IDs.
ref and populate
A connection request stores only IDs:
{ "fromUserId": "6702a1f4...", "toUserId": "6702b7c9...", "status": "interested" }{ "fromUserId": "6702a1f4...", "toUserId": "6702b7c9...", "status": "interested" }To show B a list of requests, the frontend needs the sender's name and photo, not an ID. In SQL you'd use a JOIN (Chapter 12: Databases SQL and NoSQL). In Mongoose you use ref and populate.
ref: say what the ID points to
You already added it in Chapter S2 12: Logical DB Query and Compound Indexes:
fromUserId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User", // this ID belongs to a document of the User model
required: true,
},fromUserId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User", // this ID belongs to a document of the User model
required: true,
},populate: replace the ID with the document
const requests = await ConnectionRequest.find({ toUserId: me, status: "interested" })
.populate("fromUserId", "firstName lastName photoUrl age gender about skills");const requests = await ConnectionRequest.find({ toUserId: me, status: "interested" })
.populate("fromUserId", "firstName lastName photoUrl age gender about skills");- The first argument is the path to populate (
"fromUserId"). - The second is the fields to include from the user: a space-separated string (an array also works). Without it, Mongoose fetches the entire user document, including the password hash.
Only return safe fields
Define the safe fields once and reuse them everywhere:
// src/routes/user.js
const USER_SAFE_DATA = "firstName lastName photoUrl age gender about skills";// src/routes/user.js
const USER_SAFE_DATA = "firstName lastName photoUrl age gender about skills";Never include password or emailId in data you send about other users.
The requests-received API
Endpoint: GET /user/requests/received: all pending requests sent to the logged-in user.
Thinking it through: the caller is req.user; "pending" means status interested; the frontend needs sender details, so populate fromUserId with safe fields.
// src/routes/user.js
const express = require("express");
const { userAuth } = require("../middlewares/auth");
const ConnectionRequest = require("../models/connectionRequest");
const userRouter = express.Router();
const USER_SAFE_DATA = "firstName lastName photoUrl age gender about skills";
userRouter.get("/user/requests/received", userAuth, async (req, res) => {
try {
const connectionRequests = await ConnectionRequest.find({
toUserId: req.user._id,
status: "interested",
}).populate("fromUserId", USER_SAFE_DATA);
res.json({ message: "Data fetched successfully", data: connectionRequests });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});// src/routes/user.js
const express = require("express");
const { userAuth } = require("../middlewares/auth");
const ConnectionRequest = require("../models/connectionRequest");
const userRouter = express.Router();
const USER_SAFE_DATA = "firstName lastName photoUrl age gender about skills";
userRouter.get("/user/requests/received", userAuth, async (req, res) => {
try {
const connectionRequests = await ConnectionRequest.find({
toUserId: req.user._id,
status: "interested",
}).populate("fromUserId", USER_SAFE_DATA);
res.json({ message: "Data fetched successfully", data: connectionRequests });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});find always returns an array (possibly empty), so there's no need for an if (connectionRequests) check.
The connections API
Endpoint: GET /user/connections: everyone the logged-in user is connected with.
Thinking it through:
- A connection is an
acceptedrequest. - I'm connected whether I sent the request or received it, so the query needs
$or(Chapter S2 12: Logical DB Query and Compound Indexes). - For each connection, return the other person, not me.
That last point is easy to get wrong. The original course version returns row.fromUserId for every row. For requests I sent, fromUserId is me, so my own profile appears in my connection list and the actual connection is missing. Populate both sides and pick the one that isn't me:
userRouter.get("/user/connections", userAuth, async (req, res) => {
try {
const loggedInUser = req.user;
const connectionRequests = await ConnectionRequest.find({
status: "accepted",
$or: [{ toUserId: loggedInUser._id }, { fromUserId: loggedInUser._id }],
})
.populate("fromUserId", USER_SAFE_DATA)
.populate("toUserId", USER_SAFE_DATA);
const data = connectionRequests.map((row) =>
row.fromUserId._id.equals(loggedInUser._id) ? row.toUserId : row.fromUserId
);
res.json({ data });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});
module.exports = userRouter;userRouter.get("/user/connections", userAuth, async (req, res) => {
try {
const loggedInUser = req.user;
const connectionRequests = await ConnectionRequest.find({
status: "accepted",
$or: [{ toUserId: loggedInUser._id }, { fromUserId: loggedInUser._id }],
})
.populate("fromUserId", USER_SAFE_DATA)
.populate("toUserId", USER_SAFE_DATA);
const data = connectionRequests.map((row) =>
row.fromUserId._id.equals(loggedInUser._id) ? row.toUserId : row.fromUserId
);
res.json({ data });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});
module.exports = userRouter;Note .equals() again: comparing ObjectIds with === would always be false (Chapter S2 12: Logical DB Query and Compound Indexes).
populate isn't free: the N+1 problem
populate is not a join inside MongoDB. Mongoose runs the main query, collects all the referenced IDs, then runs one extra query per populated path (User.find({ _id: { $in: [...] } })) and stitches the results together in Node.js.
That's efficient: one extra query per path, not per document. Compare it with the trap it saves you from, the N+1 query problem:
// ❌ N+1: one query for the requests, then one more query PER request
const requests = await ConnectionRequest.find({ toUserId: me });
for (const r of requests) {
r.sender = await User.findById(r.fromUserId); // 100 requests = 101 queries
}// ❌ N+1: one query for the requests, then one more query PER request
const requests = await ConnectionRequest.find({ toUserId: me });
for (const r of requests) {
r.sender = await User.findById(r.fromUserId); // 100 requests = 101 queries
}For heavy reporting queries, MongoDB's $lookup aggregation stage can do the join inside the database in a single round trip.
Try it on its own
ref and populate are easiest to see with a classic example: books that point to their author. Nothing here depends on DevTinder.
It uses mongodb-memory-server, which starts a throwaway MongoDB inside the script, so you need no Atlas account and no local install:
mkdir try-it && cd try-it
npm init -y
npm install mongoose mongodb-memory-servermkdir try-it && cd try-it
npm init -y
npm install mongoose mongodb-memory-server(The first run downloads a MongoDB binary, so it takes a minute.)
// populate-demo.js: ref + populate with authors and books
const mongoose = require("mongoose");
const { MongoMemoryServer } = require("mongodb-memory-server");
const Author = mongoose.model("Author", new mongoose.Schema({ name: String, country: String }));
const Book = mongoose.model(
"Book",
new mongoose.Schema({
title: String,
// store only the author's _id, and tell Mongoose which model it points to
author: { type: mongoose.Schema.Types.ObjectId, ref: "Author" },
})
);
async function main() {
const mongo = await MongoMemoryServer.create();
await mongoose.connect(mongo.getUri());
const ruskin = await Author.create({ name: "Ruskin Bond", country: "India" });
await Book.create({ title: "The Blue Umbrella", author: ruskin._id });
// without populate: author is just an ObjectId
const plain = await Book.findOne().lean();
console.log("plain: ", plain.author);
// with populate: Mongoose runs a second query and swaps the id for the document
const full = await Book.findOne().populate("author").lean();
console.log("populated:", full.author);
// pick only the fields you need (always do this for user data)
const slim = await Book.findOne().populate("author", "name").lean();
console.log("slim: ", slim.author);
await mongoose.disconnect();
await mongo.stop();
}
main();// populate-demo.js: ref + populate with authors and books
const mongoose = require("mongoose");
const { MongoMemoryServer } = require("mongodb-memory-server");
const Author = mongoose.model("Author", new mongoose.Schema({ name: String, country: String }));
const Book = mongoose.model(
"Book",
new mongoose.Schema({
title: String,
// store only the author's _id, and tell Mongoose which model it points to
author: { type: mongoose.Schema.Types.ObjectId, ref: "Author" },
})
);
async function main() {
const mongo = await MongoMemoryServer.create();
await mongoose.connect(mongo.getUri());
const ruskin = await Author.create({ name: "Ruskin Bond", country: "India" });
await Book.create({ title: "The Blue Umbrella", author: ruskin._id });
// without populate: author is just an ObjectId
const plain = await Book.findOne().lean();
console.log("plain: ", plain.author);
// with populate: Mongoose runs a second query and swaps the id for the document
const full = await Book.findOne().populate("author").lean();
console.log("populated:", full.author);
// pick only the fields you need (always do this for user data)
const slim = await Book.findOne().populate("author", "name").lean();
console.log("slim: ", slim.author);
await mongoose.disconnect();
await mongo.stop();
}
main();Run node populate-demo.js (your ids will differ):
plain: new ObjectId('6b122e5e90d318b5e4a804dc')
populated: {
_id: new ObjectId('6b122e5e90d318b5e4a804dc'),
name: 'Ruskin Bond',
country: 'India',
__v: 0
}
slim: { _id: new ObjectId('6b122e5e90d318b5e4a804dc'), name: 'Ruskin Bond' }plain: new ObjectId('6b122e5e90d318b5e4a804dc')
populated: {
_id: new ObjectId('6b122e5e90d318b5e4a804dc'),
name: 'Ruskin Bond',
country: 'India',
__v: 0
}
slim: { _id: new ObjectId('6b122e5e90d318b5e4a804dc'), name: 'Ruskin Bond' }- The book stores only the author's
_id. That's the "reference" inref: like a library card that says "see shelf 12", not a copy of the whole book. populate("author")tells Mongoose: "look in theAuthormodel (fromref) for this id and put the document here." Behind the scenes that's a second query.populate("author", "name")returns only the fields you list (plus_id). In DevTinder this is whyfromUserIdis populated with a safe field list, never with the password hash.
Common mistakes
- Typos in status values in queries (
"intrested"): the query silently matches nothing. - Reviewing with only
_id: anyone could accept anyone's request. Always includetoUserId: meandstatus: "interested". - Populating without a field list: you leak password hashes and emails.
- Returning
fromUserIdfor every connection: shows yourself instead of the other person. - Querying inside a loop (N+1) instead of using
populateor$in.
Key takeaways
- Think an API through: who is calling, what inputs are allowed, what must be true, how the query enforces it, what each outcome returns.
- Put ownership and state checks in the query (
_id+toUserId+status), and return the same 404 for every failure. refsays which model an ID belongs to;populate(path, fields)replaces the ID with selected fields of that document.- Always populate with a safe field list.
- In the connections list, return the other user, compared with
.equals(). populatecosts one extra query per path; avoid N+1 loops; use$lookupfor heavy joins.
Interview questions
Q1. What do ref and populate do in Mongoose?
ref in a schema tells Mongoose which model an ObjectId field refers to. populate(path, select) then replaces those IDs in query results with the referenced documents (optionally only selected fields). It's Mongoose's way of resolving relationships between collections, similar to a JOIN.
Q2. Is populate a database join?
No. Mongoose runs the main query, then issues an additional query per populated path (find({ _id: { $in: ids } })) and merges the results in application memory. A true server-side join in MongoDB is the $lookup stage of the aggregation pipeline.
Q3. What is the N+1 query problem?
Fetching a list with one query (1), then running another query for each item (N) to load related data. It produces N+1 round trips, which gets slow as N grows. Fix it by batching: populate, an $in query for all related IDs, or a $lookup/JOIN.
Q4. How do you make sure a user can only accept requests sent to them?
Never trust IDs from the client to establish identity. Take the user from the authenticated token (req.user), and include ownership in the query: findOne({ _id: requestId, toUserId: req.user._id, status: "interested" }). If no document matches, return 404, without revealing whether the request exists but belongs to someone else.
Q5. What is IDOR?
Insecure Direct Object Reference: an API that lets a user act on an object just by changing its ID in the request (/request/review/accepted/<someone-else's-request>), without checking ownership. It's one of the most common API vulnerabilities. Prevent it by checking ownership on the server for every object access, as the review query does with toUserId: req.user._id.
Q6. How do you populate multiple paths, or nested paths?
Chain calls (.populate("fromUserId", fields).populate("toUserId", fields)) or pass an array/object: .populate([{ path: "fromUserId", select: fields }, { path: "toUserId", select: fields }]). For nested population, use { path: "author", populate: { path: "company" } }.
What's next
Users can send, review and list requests. The last backend piece is the feed: which profiles should a user see? In Chapter S2 14: Building Feed API and Pagination you'll build it, excluding everyone they've already interacted with, and add pagination.