skip to Main Content

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


  1. No reason why this shouldn’t work

     app.get('/cars/:email', async (req, res) => {
       const query = { email: req.params.email };
       const result = await serviceCollection.findOne(query);
       res.send(result);
     });
    

    When the "server goes down", is it giving you an error message?

    Login or Signup to reply.
  2. Your email is missing in node js code you have to grave email from req as like this
    const email = req.query.email

    Login or Signup to reply.
  3. 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

    app.get('/carsByEmail/:email', async (req, res) => {
       const query = { email: req.params.email };
       const result = await serviceCollection.findOne(query);
       res.send(result);
     });

    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

    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);
            });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search