user3542112
user3542112

Reputation: 253

mongoose (mongodb) weird behaviour when querying with no params

I'm using Postman to post to my backend to get a user based on his username and password.

Whenever the username doesn't exist as a field in the form, a user is still returned (I only have one user at the moment and he is returned);

But, if I add the username field, it returns null unless it is the correct username, even if its empty.

this is the code:

 User.findOne({
    username: req.body.username
  }, function(err, user) {
    if(err) throw err;

    // prints null if username field is present and incorrect even if its empty
    // prints a user as json if the username field is not present
    console.log(user); 
    if(!user) {
      res.json({ success: false, message: 'Authentication failed. User not found.' });
    }

I am still checking for a password so it won't work for someone to post without a username field but it is very odd and prevents the right error message to display. Why does this happen?

Upvotes: 1

Views: 24

Answers (1)

Antoine
Antoine

Reputation: 4029

You have to check first if the parameter exists, or req.body.username will equal undefined which will result in an empty query.

findOne with an empty query will fetch the first document found, as you can get all the documents with find with an empty query.

An empty string won't result as an empty query which is why you get null (you don't have any user with '' as username).

TLDR: Check the presence of every parameter before building the query and return some 409 MissingParameterError if you are building a REST api.

Upvotes: 1

Related Questions