L
L
lil_koi2019-11-20 15:11:41
Node.js
lil_koi, 2019-11-20 15:11:41

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

2 answer(s)
H
hzzzzl, 2019-11-20
@lil_koi

const user = await User.find({_id: ObjectId(req.params.id)});  // вот тут подождать надо
res.send({ user });

I generally suspect that mongoose itself will lead to the desired type, and you can simply
await User.findOne({_id: req.params.id})

I
IDONTSUDO, 2019-11-20
@IDONTSUDO

your ID has a String data type, and mongo expects an Object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question