GeekOnGadgets
GeekOnGadgets

Reputation: 959

Mongoosedb: query by username

Problem Question: I am using MongooseDB with Nodejs and I have user schema

var UserSchema = new mongoose.Schema({
  userEmail: String
});

how would I query using the userEmail?

I tried following but no result. On my postman i get cast to ObjectId failed error

router.get('/:userEmail', function(req, res, next) {
   User.find(req.params.userEmail, function (err, userDetails) {
     if(err){
       return next(err);
     }res.json(userDetails);
   })
 });

Upvotes: 0

Views: 49

Answers (3)

notionquest
notionquest

Reputation: 39186

I am unable to reproduce your error "ObjectId failed error". However, I am adding another answer to give you more options.

The following things are slightly different from other answers:-

1) "lean()" is used to ensure that you will be returned a plain JavaScript object

2) Excluded the "_id" from JSON response though I am not sure whether you need the "Id" in the response. This is just to check whether "id" in response is causing the problem.

router.get('/:userEmail', function(req, res, next) {
    User.find({"userEmail": req.params.userEmail}, {"_id":false}).lean().exec(function(err, users) {
        if (err) {
            return next(err);
        }
        console.log(users);
        res.json(users);
    });
});

Upvotes: 1

Lucky
Lucky

Reputation: 137

Please try this syntax

router.get('/:userEmail', function(req, res, next) {
   User.find({"userEmail":req.params.userEmail}, function (err, userDetails) {
     if(err){
       return next(err);
     }res.json(userDetails);
   })
 });

You have to put condition on which field you want to query data.

Upvotes: 1

chridam
chridam

Reputation: 103335

You need to create a query object or document that has the userEmail property and a value from the req.params object. In your case, this would be:

router.get('/:userEmail', function(req, res, next) {
    User.find({ "userEmail": req.params.userEmail }, function(err, userDetails) {
        if(err){
           return next(err);
        }
        res.json(userDetails);
    });
});

Upvotes: 1

Related Questions