This is where DevTinder gets its core feature: sending a connection request. You'll design the ConnectionRequest model, write an API with every check a real app needs, use a Mongoose pre hook and logical query operators, and learn how indexes keep all of it fast as the app grows.
In this chapter you'll learn
- the
ConnectionRequestschema: references,enumand timestamps - the "send request" API, and the edge cases a thought-through API must handle
- logical operators:
$orand$and - Mongoose middleware (
pre("save")), and how it changed in Mongoose 9 - comparing ObjectIds correctly
- indexes: what they are, how they work, compound indexes, and their costs
Before you start: read Chapter S2 10: Authentication, JWT & Cookies (userAuth, req.user) and Chapter S2 11: Diving into the APIs and Express router (routers and the status names).
The ConnectionRequest model
// src/models/connectionRequest.js
const mongoose = require("mongoose");
const connectionRequestSchema = new mongoose.Schema(
{
fromUserId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User", // points to the User model (used by populate in S2 13)
required: true,
},
toUserId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
status: {
type: String,
required: true,
enum: {
values: ["ignored", "interested", "accepted", "rejected"],
message: "{VALUE} is an incorrect status type",
},
},
},
{ timestamps: true }
);
module.exports = mongoose.model("ConnectionRequest", connectionRequestSchema);// src/models/connectionRequest.js
const mongoose = require("mongoose");
const connectionRequestSchema = new mongoose.Schema(
{
fromUserId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User", // points to the User model (used by populate in S2 13)
required: true,
},
toUserId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
status: {
type: String,
required: true,
enum: {
values: ["ignored", "interested", "accepted", "rejected"],
message: "{VALUE} is an incorrect status type",
},
},
},
{ timestamps: true }
);
module.exports = mongoose.model("ConnectionRequest", connectionRequestSchema);fromUserId/toUserIdstore references to users: just their_id, like a foreign key in SQL (Chapter 12: Databases SQL and NoSQL).ref: "User"tells Mongoose which model those IDs belong to. You'll use it withpopulatein Chapter S2 13: ref, Populate and Thought Process of writing API's.enumrestrictsstatusto four exact values. Anything else fails validation with the custom message.- The collection will be called
connectionrequests(Chapter S2 06: Database, Schema, Models & Mongoose).
Thinking through the "send request" API
Endpoint: POST /request/send/:status/:toUserId, where status is interested or ignored.
Before writing code, list everything that could go wrong. This habit separates a demo from a real API:
- Is
statusone of the two statuses allowed here? (accepted/rejectedbelong to the review API.) - Is
toUserIda valid ID, and does that user exist? - Is the user sending a request to themselves?
- Does a request between these two users already exist, in either direction? (If A already sent to B, B shouldn't be able to create a second request to A; B should review A's request instead.)
Only if all checks pass do we create the request.
The code
// src/routes/request.js
const express = require("express");
const mongoose = require("mongoose");
const { userAuth } = require("../middlewares/auth");
const ConnectionRequest = require("../models/connectionRequest");
const User = require("../models/user");
const requestRouter = express.Router();
requestRouter.post("/request/send/:status/:toUserId", userAuth, async (req, res) => {
try {
const fromUserId = req.user._id; // from the JWT, never from the URL
const { status, toUserId } = req.params;
// 1. only these two statuses can be SENT
const allowedStatus = ["ignored", "interested"];
if (!allowedStatus.includes(status)) {
return res.status(400).json({ message: "Invalid status type: " + status });
}
// 2. the receiver must be a real user
if (!mongoose.isValidObjectId(toUserId)) {
return res.status(400).json({ message: "Invalid user id" });
}
const toUser = await User.findById(toUserId);
if (!toUser) {
return res.status(404).json({ message: "User not found" });
}
// 4. no existing request between the two users, in either direction
const existingRequest = await ConnectionRequest.findOne({
$or: [
{ fromUserId, toUserId },
{ fromUserId: toUserId, toUserId: fromUserId },
],
});
if (existingRequest) {
return res.status(409).json({ message: "Connection request already exists" });
}
// 3. (sending to yourself) is checked by the pre("save") hook below
const connectionRequest = new ConnectionRequest({ fromUserId, toUserId, status });
const data = await connectionRequest.save();
res.status(201).json({
message:
status === "interested"
? `${req.user.firstName} is interested in ${toUser.firstName}`
: `${req.user.firstName} ignored ${toUser.firstName}`,
data,
});
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});
module.exports = requestRouter;// src/routes/request.js
const express = require("express");
const mongoose = require("mongoose");
const { userAuth } = require("../middlewares/auth");
const ConnectionRequest = require("../models/connectionRequest");
const User = require("../models/user");
const requestRouter = express.Router();
requestRouter.post("/request/send/:status/:toUserId", userAuth, async (req, res) => {
try {
const fromUserId = req.user._id; // from the JWT, never from the URL
const { status, toUserId } = req.params;
// 1. only these two statuses can be SENT
const allowedStatus = ["ignored", "interested"];
if (!allowedStatus.includes(status)) {
return res.status(400).json({ message: "Invalid status type: " + status });
}
// 2. the receiver must be a real user
if (!mongoose.isValidObjectId(toUserId)) {
return res.status(400).json({ message: "Invalid user id" });
}
const toUser = await User.findById(toUserId);
if (!toUser) {
return res.status(404).json({ message: "User not found" });
}
// 4. no existing request between the two users, in either direction
const existingRequest = await ConnectionRequest.findOne({
$or: [
{ fromUserId, toUserId },
{ fromUserId: toUserId, toUserId: fromUserId },
],
});
if (existingRequest) {
return res.status(409).json({ message: "Connection request already exists" });
}
// 3. (sending to yourself) is checked by the pre("save") hook below
const connectionRequest = new ConnectionRequest({ fromUserId, toUserId, status });
const data = await connectionRequest.save();
res.status(201).json({
message:
status === "interested"
? `${req.user.firstName} is interested in ${toUser.firstName}`
: `${req.user.firstName} ignored ${toUser.firstName}`,
data,
});
} catch (err) {
res.status(400).send("ERROR: " + err.message);
}
});
module.exports = requestRouter;Some things to notice:
fromUserIdcomes fromreq.user(set byuserAuthfrom the verified JWT), never from the request. Otherwise anyone could send requests "from" someone else.mongoose.isValidObjectIdrejects garbage IDs early with a clear 400, instead of a confusingCastError.409 Conflictis the right status for "this already exists" (Chapter S2 05: Middlewares and Error Handlers).
Logical operators: $or and $and
The duplicate check uses $or: "match documents where any of these conditions is true".
{
$or: [
{ fromUserId: A, toUserId: B }, // A → B already exists
{ fromUserId: B, toUserId: A }, // or B → A already exists
];
}{
$or: [
{ fromUserId: A, toUserId: B }, // A → B already exists
{ fromUserId: B, toUserId: A }, // or B → A already exists
];
}The others you'll use:
| Operator | Meaning | Example |
|---|---|---|
$or | any condition is true | { $or: [{ city: "Pune" }, { city: "Mumbai" }] } |
$and | all conditions are true | { $and: [{ age: { $gte: 18 } }, { age: { $lte: 30 } }] } |
$nor | none is true | { $nor: [{ status: "rejected" }] } |
$in / $nin | value is (not) in a list | { _id: { $nin: [id1, id2] } } (Chapter S2 14: Building Feed API and Pagination) |
$ne | not equal | { _id: { $ne: myId } } |
Listing several fields in one object is already an implicit AND: { fromUserId: A, toUserId: B } means "fromUserId is A and toUserId is B". You need an explicit $and mostly when you have two conditions on the same field.
Mongoose middleware: pre("save")
Mongoose middleware (also called hooks) are functions that run automatically before (pre) or after (post) certain operations, like save or validate. They're a good place for rules that must always hold, no matter which route saves the document.
DevTinder uses one to stop users from sending a request to themselves:
// src/models/connectionRequest.js
connectionRequestSchema.pre("save", function () {
const connectionRequest = this; // the document being saved
if (connectionRequest.fromUserId.equals(connectionRequest.toUserId)) {
throw new Error("You cannot send a connection request to yourself!");
}
});// src/models/connectionRequest.js
connectionRequestSchema.pre("save", function () {
const connectionRequest = this; // the document being saved
if (connectionRequest.fromUserId.equals(connectionRequest.toUserId)) {
throw new Error("You cannot send a connection request to yourself!");
}
});Two important details.
1. Use function, not an arrow function
this must be the document being saved. Arrow functions don't have their own this (Chapter S2 10: Authentication, JWT & Cookies had the same rule for schema methods).
2. Don't use next on Mongoose 9
The original course code writes the hook with a next callback:
connectionRequestSchema.pre("save", function (next) {
// ...check...
next(); // ❌ on Mongoose 9: "next is not a function"
});connectionRequestSchema.pre("save", function (next) {
// ...check...
next(); // ❌ on Mongoose 9: "next is not a function"
});That worked up to Mongoose 8. Mongoose 9 (the current version) no longer passes next to pre hooks. We tested this hook style on Mongoose 9 (using a pre("validate") hook, which goes through the same hook machinery): calling next() throws next is not a function whenever the check passes, so with a pre("save") hook every valid request would fail to save. The version shown above, which throws to reject and simply returns to continue (or is an async function), works on all versions. Prefer it.
Comparing ObjectIds: .equals(), never ===
fromUserId and toUserId are ObjectId objects. Two different objects are never === in JavaScript, even when they hold the same ID. We checked it:
const x = new mongoose.Types.ObjectId();
const y = new mongoose.Types.ObjectId(x.toString()); // same value
x === y; // false ❌ (different objects)
x.equals(y); // true ✅
x.toString() === y.toString(); // true ✅const x = new mongoose.Types.ObjectId();
const y = new mongoose.Types.ObjectId(x.toString()); // same value
x === y; // false ❌ (different objects)
x.equals(y); // true ✅
x.toString() === y.toString(); // true ✅A check like if (fromUserId === toUserId) would never be true, so the self-request rule would silently never run.
Indexes: making queries fast
The problem
The duplicate check runs on every request: findOne({ $or: [...] }). With 10 documents, that's instant. With 10 million, MongoDB has to look at every document to find matches. That's called a collection scan (COLLSCAN), and it gets slower as data grows.
What is an index?
An index is a separate, sorted data structure that maps field values to the documents that contain them, like the index at the back of a book: to find "event loop", you look it up in the sorted index and jump straight to page 214, instead of reading the whole book.
MongoDB stores indexes as B-trees, which can find a value among millions in just a few steps.
- MongoDB always indexes
_idautomatically. unique: truein a Mongoose schema makes Mongoose create a unique index when the app starts (theautoIndexoption) (Chapter S2 08: Data Sanitization & Schema Validations).index: truecreates a normal index on one field:
firstName: { type: String, index: true },firstName: { type: String, index: true },You can see whether a query uses an index with explain:
const plan = await ConnectionRequest.find({ fromUserId: id }).explain("executionStats");
// look for "IXSCAN" (index scan, good) vs "COLLSCAN" (full scan)const plan = await ConnectionRequest.find({ fromUserId: id }).explain("executionStats");
// look for "IXSCAN" (index scan, good) vs "COLLSCAN" (full scan)Compound indexes
A compound index covers several fields together. The duplicate check filters on fromUserId and toUserId, so:
connectionRequestSchema.index({ fromUserId: 1, toUserId: 1 });connectionRequestSchema.index({ fromUserId: 1, toUserId: 1 });(1 = ascending order, -1 = descending. For equality lookups, the direction doesn't matter.)
Field order matters. A compound index is sorted by the first field, then by the second within each first value, like a phone book sorted by last name, then first name:
| Query filters on | Can use { fromUserId: 1, toUserId: 1 }? |
|---|---|
fromUserId + toUserId | ✅ yes |
fromUserId only | ✅ yes (it's a prefix of the index) |
toUserId only | ❌ no: like finding everyone named "Rahul" in a phone book sorted by last name |
That's why DevTinder's "requests received" API, which filters by toUserId and status (Chapter S2 13: ref, Populate and Thought Process of writing API's), benefits from its own index:
connectionRequestSchema.index({ toUserId: 1, status: 1 });connectionRequestSchema.index({ toUserId: 1, status: 1 });The cost of indexes
Indexes aren't free:
- Storage: each index takes disk space and RAM.
- Slower writes: every insert, update and delete must also update every index on the collection.
- Maintenance: unused indexes still cost all of the above.
So: index the fields your frequent queries filter and sort on, check with explain, and don't add indexes "just in case".
In production, many teams turn Mongoose's autoIndex off and create indexes deliberately (with a migration script or in Atlas), because building an index on a large collection can be slow and resource-heavy.
Try it on its own
The three tools of this chapter (logical operators, pre("save") hooks and compound indexes) work on any collection. This script uses a tiny "follow" model instead of connection requests, so you can run it without the DevTinder project.
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.)
// query-demo.js: $or / $and, a pre("save") hook, and a compound index
const mongoose = require("mongoose");
const { MongoMemoryServer } = require("mongodb-memory-server");
const followSchema = new mongoose.Schema({
from: { type: String, required: true },
to: { type: String, required: true },
});
// runs before every save(); throwing an error cancels the save (Mongoose 9: no next)
followSchema.pre("save", function () {
if (this.from === this.to) throw new Error("You can't follow yourself");
});
// compound index: fast lookups by (from, to), and no duplicate pairs
followSchema.index({ from: 1, to: 1 }, { unique: true });
const Follow = mongoose.model("Follow", followSchema);
async function main() {
const mongo = await MongoMemoryServer.create(); // a throwaway MongoDB in memory
await mongoose.connect(mongo.getUri());
await Follow.init(); // wait until the indexes are built
await Follow.create([{ from: "asha", to: "ravi" }, { from: "ravi", to: "meera" }]);
// $or: any condition may match. "Is there a follow between asha and ravi, either direction?"
const between = await Follow.find({
$or: [{ from: "asha", to: "ravi" }, { from: "ravi", to: "asha" }],
});
console.log("$or found:", between.length);
// $and: every condition must match (same as listing both fields in one object)
const exact = await Follow.find({ $and: [{ from: "ravi" }, { to: "meera" }] });
console.log("$and found:", exact.length);
try {
await Follow.create({ from: "meera", to: "meera" });
} catch (err) {
console.log("pre hook:", err.message);
}
try {
await Follow.create({ from: "asha", to: "ravi" });
} catch (err) {
console.log("unique index:", err.code); // 11000 = duplicate key
}
// explain() shows how MongoDB ran the query: IXSCAN = it used an index
const plan = await Follow.find({ from: "asha", to: "ravi" }).explain();
console.log("plan:", plan.queryPlanner.winningPlan.inputStage.stage);
await mongoose.disconnect();
await mongo.stop();
}
main();// query-demo.js: $or / $and, a pre("save") hook, and a compound index
const mongoose = require("mongoose");
const { MongoMemoryServer } = require("mongodb-memory-server");
const followSchema = new mongoose.Schema({
from: { type: String, required: true },
to: { type: String, required: true },
});
// runs before every save(); throwing an error cancels the save (Mongoose 9: no next)
followSchema.pre("save", function () {
if (this.from === this.to) throw new Error("You can't follow yourself");
});
// compound index: fast lookups by (from, to), and no duplicate pairs
followSchema.index({ from: 1, to: 1 }, { unique: true });
const Follow = mongoose.model("Follow", followSchema);
async function main() {
const mongo = await MongoMemoryServer.create(); // a throwaway MongoDB in memory
await mongoose.connect(mongo.getUri());
await Follow.init(); // wait until the indexes are built
await Follow.create([{ from: "asha", to: "ravi" }, { from: "ravi", to: "meera" }]);
// $or: any condition may match. "Is there a follow between asha and ravi, either direction?"
const between = await Follow.find({
$or: [{ from: "asha", to: "ravi" }, { from: "ravi", to: "asha" }],
});
console.log("$or found:", between.length);
// $and: every condition must match (same as listing both fields in one object)
const exact = await Follow.find({ $and: [{ from: "ravi" }, { to: "meera" }] });
console.log("$and found:", exact.length);
try {
await Follow.create({ from: "meera", to: "meera" });
} catch (err) {
console.log("pre hook:", err.message);
}
try {
await Follow.create({ from: "asha", to: "ravi" });
} catch (err) {
console.log("unique index:", err.code); // 11000 = duplicate key
}
// explain() shows how MongoDB ran the query: IXSCAN = it used an index
const plan = await Follow.find({ from: "asha", to: "ravi" }).explain();
console.log("plan:", plan.queryPlanner.winningPlan.inputStage.stage);
await mongoose.disconnect();
await mongo.stop();
}
main();Run node query-demo.js:
$or found: 1
$and found: 1
pre hook: You can't follow yourself
unique index: 11000
plan: IXSCAN$or found: 1
$and found: 1
pre hook: You can't follow yourself
unique index: 11000
plan: IXSCAN$orfinds the asha → ravi follow, and would also find ravi → asha. That's the "is there already a request between these two users, in either direction?" check from this chapter.$andneeds every condition to match. Writing{ from: "ravi", to: "meera" }means the same thing;$andmatters when you combine several$orgroups.- The
pre("save")hook stops the bad document before it reaches the database.create()callssave(), so the hook runs. - The unique compound index rejects a second asha → ravi document with error code
11000(duplicate key). explain()reportsIXSCAN(index scan): MongoDB used the{ from: 1, to: 1 }index. Without the index it would sayCOLLSCAN, meaning it read every document.
Common mistakes
- Taking
fromUserIdfrom the request instead ofreq.user. - Not checking that the receiver exists, or not checking both directions for duplicates.
- Comparing ObjectIds with
===. - Callback-style
prehooks (next) on Mongoose 9: every save fails. - Arrow functions in hooks:
thisis undefined. - A compound index in the wrong order for your queries, or indexing every field.
Key takeaways
ConnectionRequeststores references (fromUserId,toUserIdwithref: "User") and astatusrestricted byenum.- A real API checks: allowed status, valid and existing receiver, no self-request, no duplicate in either direction.
$ormatches if any condition is true; multiple fields in one filter are an implicit AND.pre("save")hooks enforce rules on every save. Usefunctionand throw to reject; don't usenexton Mongoose 9.- Compare ObjectIds with
.equals(). - Indexes (B-trees) turn full scans into fast lookups. Compound index field order matters (prefix rule). Indexes cost storage and write speed.
Interview questions
Q1. What is an index in MongoDB, and why use one?
An index is a sorted data structure (a B-tree) that stores the values of one or more fields with pointers to their documents. It lets MongoDB find matching documents without scanning the whole collection (IXSCAN instead of COLLSCAN), making reads much faster. The cost: extra storage, and slower writes, since every index must be updated on insert, update and delete.
Q2. What is a compound index, and why does the field order matter?
A compound index covers multiple fields, e.g. { fromUserId: 1, toUserId: 1 }. It's sorted by the first field, then the second. It supports queries on a prefix of its fields (fromUserId, or fromUserId + toUserId) but not on toUserId alone. A common guideline is the ESR rule: put fields used for Equality first, then Sort fields, then Range fields.
Q3. What are Mongoose middleware (hooks)?
Functions that run automatically before (pre) or after (post) operations such as save, validate, deleteOne or find. They're used for cross-cutting rules: hashing passwords before save, validating relationships, logging, cascading deletes. In document middleware, this is the document. In Mongoose 9, pre hooks no longer receive a next callback; throw an error (or return a rejected promise) to stop the operation.
Q4. How do you compare two ObjectIds?
With id1.equals(id2), or by comparing their string forms (id1.toString() === id2.toString()). === compares object references, so two ObjectId instances with the same value are not ===.
Q5. How would you prevent duplicate connection requests between two users?
In the API, check for an existing request in both directions with $or before creating one, and answer 409 if found. For a guarantee under concurrent requests, also enforce it in the database, for example a unique compound index on a normalized pair (store the two IDs in sorted order in extra fields and make that pair unique), because two simultaneous requests could both pass the API check.
Q6. What is the difference between $or and $in?
$in checks one field against a list of values: { city: { $in: ["Pune", "Mumbai"] } }. $or combines whole conditions, possibly on different fields: { $or: [{ city: "Pune" }, { age: { $lt: 18 } }] }. For alternatives on a single field, $in is simpler and often faster.
Q7. How do you check whether a MongoDB query uses an index?
Run it with .explain("executionStats") (in Mongoose or the shell) and look at the winning plan: IXSCAN means an index was used; COLLSCAN means a full collection scan. Also compare totalDocsExamined with nReturned: a good index examines about as many documents as it returns.
What's next
Requests can now be sent. In Chapter S2 13: ref, Populate and Thought Process of writing API's the receiver gets to review them (accept or reject), and you'll use ref and populate to show who sent each request, plus build the connections list.