I am trying to retrieve todo by id. Code for getTodo service method is as below:
const getTodo = async (id, userId) => {
const todo = await Todo.findOne({ id: id, userId: userId });
return todo;
};
code from router which acts as a controller is as below:
router.get("/:id", tokenValidation.validate, async (req, res) => {
const serverResponse = { ...defaultResponse };
try {
const decodedToken = jwt.decode(
req.headers.authorization.split(" ")[1].trim()
);
const getTodo = await todoService.getTodo(req.params.id, decodedToken.id);
serverResponse.status = 200;
serverResponse.body = getTodo;
serverResponse.message = "Get todo by id";
} catch (error) {
serverResponse.message = error.message;
}
return res.status(serverResponse.status).send(serverResponse);
});
But the result is always null, on calling:
http://localhost:3000/api/v1/todos/60422718e9db822de8531e87
{
"status": 200,
"message": "Get todo by id",
"body": null
}
What is missing in findOne method. Todo with id exists in the collection but is not returned. Please let me know what is missing.
Thanks
You must use with AND operator
const getTodo = async(id, userId) => {
const todo = await Todo.findOne({
$and: [{
_id: id
},
{
userId: userId
}
]
});
return todo;
};
So this will return results with the combined conditions.
const getTodo = async (id, userId) => {
const todo = await Todo.findOne({ id: id, userId: userId });
return todo;
};
mongoose does not have "id" property. it has _id so you should query:
const todo = await Todo.findOne({ _id: id, userId: userId })
you dont need to pass two arguments. they both reflect same. "id" is already unique. you could just query:
const todo = await Todo.findById(id)