Russ
Russ

Reputation: 21

The mongoose's findOne method is not recognizing my variables?

I'm new to node.js, express, and mongoose. Below is my code.

Please note that I've hard coded the value "P4" in the findOne method and everything works as expected.

When I try to use the product variable its not being recognized by the findOne method.

What am i doing wrong?

router.get('/search', function(req, res) {
var product = req.body.product;
MyData.findOne({product: **'P4'**}, function(err, doc) { 
    if (doc)
    {
        console.log('Product Found', doc);
        res.render('index',{ids: doc});
    } 
    else if (err)
    { 
          res.redirect('/');
          console.error ('Doc Not found', doc);
    }
  });
});

Upvotes: 0

Views: 515

Answers (2)

Narayan Singh
Narayan Singh

Reputation: 1232

Very basic tip in coding. Always Always console.log(the variable). If its coming undefined. Means the variable is not available at that place. Try to debug step by step.

Upvotes: 0

robertklep
robertklep

Reputation: 203554

You're defining a GET route, which (generally) gets passed parameters using query strings. In other words, /search?product=P4.

This means that instead of req.body, you should use req.query to access the product parameter:

var product = req.query.product;

Upvotes: 1

Related Questions