The feed is DevTinder's main screen: profiles you swipe through, one at a time. Two questions make it interesting: which users should appear (not yourself, not anyone you've already interacted with), and how many to send at once. This chapter answers both, with $nin and pagination.
In this chapter you'll learn
- how to decide who belongs in the feed, and turn that into a query
- using a JavaScript
Setto collect IDs without duplicates - the
$ninand$neoperators - pagination with
skipandlimit, and why you must also sort - validating
pageandlimitfrom the query string - the limits of skip-based pagination, and cursor pagination
Before you start: read Chapter S2 12: Logical DB Query and Compound Indexes (statuses, $or) and Chapter S2 13: ref, Populate and Thought Process of writing API's (thinking through an API).
Who should appear in my feed?
Let's apply the method from Chapter S2 13: ref, Populate and Thought Process of writing API's. I'm logged in as A. The feed should show every user except:
- myself
- people I've already sent a request to (
interestedorignored): I already decided - people who sent me a request: I'll see them in "requests received" instead
- people I'm already connected with (
accepted) or who rejected me / whom I rejected
Points 2–4 have something in common: any ConnectionRequest between A and that user, in either direction, whatever its status. That's one query:
const connectionRequests = await ConnectionRequest.find({
$or: [{ fromUserId: loggedInUser._id }, { toUserId: loggedInUser._id }],
}).select("fromUserId toUserId"); // we only need the two IDsconst connectionRequests = await ConnectionRequest.find({
$or: [{ fromUserId: loggedInUser._id }, { toUserId: loggedInUser._id }],
}).select("fromUserId toUserId"); // we only need the two IDs.select(...) fetches only the listed fields, so less data travels from the database.
Collecting the IDs to hide: Set
Each request involves two users, and the same person can appear in several requests. A JavaScript Set stores unique values only: adding something twice keeps one copy.
const hideUsersFromFeed = new Set();
connectionRequests.forEach((request) => {
hideUsersFromFeed.add(request.fromUserId.toString());
hideUsersFromFeed.add(request.toUserId.toString());
});const hideUsersFromFeed = new Set();
connectionRequests.forEach((request) => {
hideUsersFromFeed.add(request.fromUserId.toString());
hideUsersFromFeed.add(request.toUserId.toString());
});.toString()matters: ObjectIds are objects, and two different ObjectId objects with the same value are different entries in aSet(the same===problem from Chapter S2 12: Logical DB Query and Compound Indexes). Strings with the same value are equal, so duplicates really collapse.- Name the loop variable
request(orrow), notreq: inside a route handler,reqalready means the HTTP request, and shadowing it causes confusing bugs.
Note what the Set does and doesn't do: it removes duplicates in Node.js, which keeps the exclusion list short. It doesn't make the database query itself faster; that's the job of indexes (Chapter S2 12: Logical DB Query and Compound Indexes).
The query: $nin
$nin ("not in") matches documents whose field value is not in a list:
const users = await User.find({
_id: { $nin: [...hideUsersFromFeed, loggedInUser._id] },
}).select(USER_SAFE_DATA);const users = await User.find({
_id: { $nin: [...hideUsersFromFeed, loggedInUser._id] },
}).select(USER_SAFE_DATA);Adding my own ID to the $nin list covers point 1, so there's no need for a separate $ne condition (the course version uses $and with $nin plus $ne, which gives the same result).
| Operator | Meaning |
|---|---|
$in | value is in the list |
$nin | value is not in the list |
$ne | value is not equal to one value |
Pagination
DevTinder could have 100,000 users. Sending all of them in one response would be slow for the database, the network and the phone receiving it. Pagination sends the results in pages.
The client asks for a page with the query string (Chapter S2 04: Routing and Request handlers):
GET /user/feed?page=1&limit=10 → users 1–10
GET /user/feed?page=2&limit=10 → users 11–20
GET /user/feed?page=3&limit=10 → users 21–30GET /user/feed?page=1&limit=10 → users 1–10
GET /user/feed?page=2&limit=10 → users 11–20
GET /user/feed?page=3&limit=10 → users 21–30Two database methods do the work:
limit(n): return at mostndocuments.skip(n): skip the firstndocuments.
The formula that connects them:
skip = (page - 1) × limitskip = (page - 1) × limitFor page 3 with 10 per page: skip (3 − 1) × 10 = 20, then take 10, which gives users 21–30.
Validate the input
page and limit arrive as strings from the URL, and a client can send anything. We tested how this handles bad input:
const page = Math.max(parseInt(req.query.page) || 1, 1);
const limit = Math.min(Math.max(parseInt(req.query.limit) || 10, 1), 50);
const skip = (page - 1) * limit;const page = Math.max(parseInt(req.query.page) || 1, 1);
const limit = Math.min(Math.max(parseInt(req.query.limit) || 10, 1), 50);
const skip = (page - 1) * limit;| Query string | Result |
|---|---|
| (none) | page 1, limit 10, skip 0 |
?page=2&limit=10 | page 2, limit 10, skip 10 |
?page=0 or ?page=-3 | page 1 (a negative skip would make MongoDB throw an error) |
?page=abc&limit=500 | page 1, limit 50 (capped so nobody can request 100,000 users at once) |
Always sort before paginating
Without .sort(), MongoDB doesn't promise any order, and the order can change between requests. Page 2 might then repeat users from page 1, or skip some. Sort on something unique and stable, like _id:
.sort({ _id: 1 }).sort({ _id: 1 })The complete feed API
// src/routes/user.js
userRouter.get("/user/feed", userAuth, async (req, res) => {
try {
const loggedInUser = req.user;
// pagination input, validated
const page = Math.max(parseInt(req.query.page) || 1, 1);
const limit = Math.min(Math.max(parseInt(req.query.limit) || 10, 1), 50);
const skip = (page - 1) * limit;
// everyone I've interacted with, in either direction
const connectionRequests = await ConnectionRequest.find({
$or: [{ fromUserId: loggedInUser._id }, { toUserId: loggedInUser._id }],
}).select("fromUserId toUserId");
const hideUsersFromFeed = new Set();
connectionRequests.forEach((request) => {
hideUsersFromFeed.add(request.fromUserId.toString());
hideUsersFromFeed.add(request.toUserId.toString());
});
hideUsersFromFeed.add(loggedInUser._id.toString()); // and myself
const users = await User.find({ _id: { $nin: [...hideUsersFromFeed] } })
.select(USER_SAFE_DATA)
.sort({ _id: 1 })
.skip(skip)
.limit(limit);
res.json({ data: users });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});// src/routes/user.js
userRouter.get("/user/feed", userAuth, async (req, res) => {
try {
const loggedInUser = req.user;
// pagination input, validated
const page = Math.max(parseInt(req.query.page) || 1, 1);
const limit = Math.min(Math.max(parseInt(req.query.limit) || 10, 1), 50);
const skip = (page - 1) * limit;
// everyone I've interacted with, in either direction
const connectionRequests = await ConnectionRequest.find({
$or: [{ fromUserId: loggedInUser._id }, { toUserId: loggedInUser._id }],
}).select("fromUserId toUserId");
const hideUsersFromFeed = new Set();
connectionRequests.forEach((request) => {
hideUsersFromFeed.add(request.fromUserId.toString());
hideUsersFromFeed.add(request.toUserId.toString());
});
hideUsersFromFeed.add(loggedInUser._id.toString()); // and myself
const users = await User.find({ _id: { $nin: [...hideUsersFromFeed] } })
.select(USER_SAFE_DATA)
.sort({ _id: 1 })
.skip(skip)
.limit(limit);
res.json({ data: users });
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});When skip-based pagination isn't enough
skip(n) has a hidden cost: to skip 100,000 documents, MongoDB still has to walk past all 100,000 of them. Deep pages get slower and slower.
Large apps use cursor-based pagination (also called keyset pagination) instead: "give me 10 users with an _id greater than the last one I saw":
// GET /user/feed?after=6702a1f4c3e9b8a1d2f4e5a6
const filter = { _id: { $nin: hidden } };
if (req.query.after) filter._id.$gt = req.query.after;
const users = await User.find(filter).sort({ _id: 1 }).limit(10);
// the client sends the last user's _id as "after" to get the next page// GET /user/feed?after=6702a1f4c3e9b8a1d2f4e5a6
const filter = { _id: { $nin: hidden } };
if (req.query.after) filter._id.$gt = req.query.after;
const users = await User.find(filter).sort({ _id: 1 }).limit(10);
// the client sends the last user's _id as "after" to get the next pageUsing the _id index, this is equally fast on page 1 and page 10,000. It's what infinite-scroll feeds usually use. The trade-off: you can't jump straight to "page 57".
Offset (skip/limit) | Cursor (_id > last) | |
|---|---|---|
| Jump to any page | ✅ yes | ❌ no, only next/previous |
| Speed on deep pages | slows down | stays fast |
| Stable when data changes | items can shift between pages | stable |
| Good for | admin tables with page numbers | feeds, infinite scroll |
Try it on its own
The feed is really two general techniques: exclude what the user has already seen ($nin) and return one page at a time (skip + limit). Here they are on a plain product list, with no users or connection requests involved.
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.)
// feed-demo.js: hide some documents with $nin, then paginate with skip/limit
const mongoose = require("mongoose");
const { MongoMemoryServer } = require("mongodb-memory-server");
const Product = mongoose.model("Product", new mongoose.Schema({ name: String }));
async function main() {
const mongo = await MongoMemoryServer.create();
await mongoose.connect(mongo.getUri());
const names = ["Pen", "Book", "Lamp", "Mug", "Bag", "Cap", "Fan"];
const products = await Product.create(names.map((name) => ({ name })));
// the user already saw these two: collect their ids in a Set (no duplicates)
const seen = new Set([products[1]._id.toString(), products[3]._id.toString()]);
async function getPage(page, limit) {
const skip = (page - 1) * limit; // page 1 → skip 0, page 2 → skip 3...
return Product.find({ _id: { $nin: [...seen] } }) // $nin = "not in this list"
.sort({ _id: 1 }) // a fixed order, so pages don't overlap
.skip(skip)
.limit(limit)
.lean();
}
for (const page of [1, 2, 3]) {
const items = await getPage(page, 3);
console.log(`page ${page}:`, items.map((p) => p.name));
}
await mongoose.disconnect();
await mongo.stop();
}
main();// feed-demo.js: hide some documents with $nin, then paginate with skip/limit
const mongoose = require("mongoose");
const { MongoMemoryServer } = require("mongodb-memory-server");
const Product = mongoose.model("Product", new mongoose.Schema({ name: String }));
async function main() {
const mongo = await MongoMemoryServer.create();
await mongoose.connect(mongo.getUri());
const names = ["Pen", "Book", "Lamp", "Mug", "Bag", "Cap", "Fan"];
const products = await Product.create(names.map((name) => ({ name })));
// the user already saw these two: collect their ids in a Set (no duplicates)
const seen = new Set([products[1]._id.toString(), products[3]._id.toString()]);
async function getPage(page, limit) {
const skip = (page - 1) * limit; // page 1 → skip 0, page 2 → skip 3...
return Product.find({ _id: { $nin: [...seen] } }) // $nin = "not in this list"
.sort({ _id: 1 }) // a fixed order, so pages don't overlap
.skip(skip)
.limit(limit)
.lean();
}
for (const page of [1, 2, 3]) {
const items = await getPage(page, 3);
console.log(`page ${page}:`, items.map((p) => p.name));
}
await mongoose.disconnect();
await mongo.stop();
}
main();Run node feed-demo.js:
page 1: [ 'Pen', 'Lamp', 'Bag' ]
page 2: [ 'Cap', 'Fan' ]
page 3: []page 1: [ 'Pen', 'Lamp', 'Bag' ]
page 2: [ 'Cap', 'Fan' ]
page 3: []BookandMugnever appear: their ids are in theseenset, and$nin("not in") filters them out inside the database.- Pagination uses
skip = (page - 1) * limit. Page 1 skips 0, page 2 skips 3. Page 2 has only two items because just five products are left. - An empty page means the client has reached the end. The DevTinder UI shows "No new users found!" at that point (Chapter S2 17: DevTinder UI - Part 3).
sortgives the results a fixed order. Without it, MongoDB doesn't promise the same order on every query, so an item could show up on two pages or on none.
Common mistakes
- No pagination: sending the whole collection.
- Paginating without
.sort(): duplicate or missing items between pages. - Not validating
page/limit: negative skips crash the query; huge limits overload the server. - Putting ObjectIds (not strings) in a
Set: duplicates aren't removed. - Shadowing
reqin aforEach((req) => ...)inside a route. - Sending full user documents instead of
USER_SAFE_DATA.
Key takeaways
- The feed excludes yourself and anyone with a connection request in either direction.
- Collect the IDs to hide in a
Setof strings, then query with$nin. - Pagination:
skip = (page − 1) × limit, withlimitcapped (for example at 50). - Always
.sort()beforeskip/limitfor stable pages. pageandlimitcome fromreq.queryas strings: parse and clamp them.- For deep or infinite feeds, cursor pagination (
_id > lastId) scales better thanskip.
Interview questions
Q1. How do you implement pagination in a REST API?
Accept page and limit (or offset/limit) as query parameters, validate them and cap limit, compute skip = (page − 1) × limit, and run the query with a stable sort, skip and limit. Optionally return metadata like total (via countDocuments) or hasNextPage. For large or fast-changing datasets, use cursor-based pagination instead.
Q2. What's the difference between offset and cursor pagination?
Offset pagination skips N records (skip/limit): simple, and supports jumping to any page, but slow on deep pages, and items shift when data changes. Cursor pagination returns records after a marker (like the last _id) using an index: consistently fast and stable, but only supports next/previous, not random page access.
Q3. Why must you sort when paginating?
Without an explicit sort, the database can return documents in any order, and that order can differ between queries. Pages may then overlap or miss documents. Sorting on a unique, stable field (like _id, or createdAt plus _id) makes each page well-defined.
Q4. What do $in and $nin do?
$in matches documents where a field's value is in a given array; $nin matches where it's not in the array (and also documents where the field doesn't exist). For example, { _id: { $nin: idsToHide } } excludes those documents.
Q5. What is a JavaScript Set, and why use it here?
A Set is a collection of unique values: adding an existing value has no effect, and lookups with has() are fast. It's ideal for collecting IDs that may appear several times. Store primitive strings, not objects, because Set compares objects by reference.
Q6. How would you make this feed faster for a user with thousands of interactions?
Make sure both ConnectionRequest queries are indexed ({ fromUserId: 1 }, { toUserId: 1 }), select only the needed fields, and use cursor pagination. With very large exclusion lists, $nin itself gets expensive; you could move the logic into an aggregation pipeline ($lookup against requests), precompute feed candidates in the background, or cache them (for example in Redis).
What's next
The backend is complete. Time to build what users actually see: in Chapter S2 15: DevTinder UI - Part 1 you'll start the React frontend with Vite, Tailwind CSS, DaisyUI and React Router.