How can I get data by email from MongoDB? Here is an example:
_id: Objectid('6274e58826914a298567e5f8'),
"name": "Vauxhall Mokka",
"supplier": "Vauxhall",
"email": "[email protected]",
"price": 30000,
"quantity": 30,
"img": "https://i.ibb.co/SQqBNXy/getImage.png",
"sold": 0
I can easily get the item by _id with this code:
app.get('/cars/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: ObjectId(id) };
const result = await serviceCollection.findOne(query);
res.send(result);
});
But why I couldn’t do the same with email? when I apply '/cars/:email'
, the server goes down. If I get the item with id, then why cannot get it with the email?
3
Answers
No reason why this shouldn’t work
When the "server goes down", is it giving you an error message?
Your email is missing in node js code you have to grave email from req as like this
const email = req.query.email
the problem is you already have another endpoint with "/cars/" you need to change "/(here)/" … like "/carsByEmail/:email". This happens when you declare another same endpoint with app.get method. You should try this enter code here
you already have this endpoint, this two are (1)=> "/cars/:id" and (2)=> "/cars/:email" the same get method. so that’s why it’s giving you BSONType error. and it also collaborates with the other same endpoint. So you should change the main endpoint name.. Like (1)=> "/carsById/:id" and (2)=> "/carsByEmail/:email" now everything is perfect withe the same get/put/patch method. just change the main part of the API endpoint. Thank you