Answer the question
In order to leave comments, you need to log in
Why don't ObjectIDs work?
I have code that searches by _id. If you do it directly by id, as from the 5dd44dafc6f4762b80b8e5ff database, then everything is fine. I looked at stackoverflow.com how to search by id number, i.e. by "1", not "5dd44dafc6f4762b80b8e5ff".
got this
var ObjectId = require('mongoose').Types.ObjectId;
exports.getById = async(req, res) => {
try {
const user = find({_id: ObjectId(req.params.id)});
res.send({ user });
} catch (err) {
res.send({status: 404, message: 'not found'})
}
}
but it doesn't work. Why?
Before that it was
exports.getById = async (req, res) => {
const id = req.params.id;
const user = await User.findById(id).exec(); // Venet promise, so await is needed. {} - find all documents
res.send({ user });
}
Answer the question
In order to leave comments, you need to log in
const user = await User.find({_id: ObjectId(req.params.id)}); // вот тут подождать надо
res.send({ user });
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question