Skip to content

User Routes

Course: PayTM project - chapter 8

User should be allowed to optionally send either or all of

  1. password
  2. firstName
  3. lastName Whatever they send, we need to update it in the database for the user. Use the middleware we defined in the last section to authenticate the user

Method: PUT Route: /api/v1/user Body:

{
password: "new_password",
firstName: "updated_first_name",
lastName: "updated_first_name",
}

Response:

Status code - 200

{
message: "Updated successfully"
}

Status code - 411 (Password is too small…)

{
message: "Error while updating information"
}
Solution
const { authMiddleware } = require("../middleware");
// other auth routes
const updateBody = zod.object({
password: zod.string().optional(),
firstName: zod.string().optional(),
lastName: zod.string().optional(),
})
router.put("/", authMiddleware, async (req, res) => {
const { success } = updateBody.safeParse(req.body)
if (!success) {
res.status(411).json({
message: "Error while updating information"
})
}
await User.updateOne({ _id: req.userId }, req.body);
res.json({
message: "Updated successfully"
})
})

2. Route to get users from the backend, filterable via firstName/lastName

Section titled “2. Route to get users from the backend, filterable via firstName/lastName”

This is needed so users can search for their friends and send them money

Method: GET Route: /api/v1/user/bulk Query Parameter: ?filter=harkirat

Response:

Status code - 200

{
users: [{
firstName: "",
lastName: "",
_id: "id of the user"
}]
}
Hints

https://stackoverflow.com/questions/7382207/mongooses-find-method-with-or-condition-does-not-work-properly

https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like

Solution
router.get("/bulk", async (req, res) => {
const filter = req.query.filter || "";
const users = await User.find({
$or: [{
firstName: {
"$regex": filter
}
}, {
lastName: {
"$regex": filter
}
}]
})
res.json({
user: users.map(user => ({
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
_id: user._id
}))
})
})