Nic Gaudio
Nic Gaudio

Reputation: 25

How to find mongoDB Object with Express, Mongoskin, and Node.js

I am trying to create a login page by asking for a user's credentials and then attempting to find that user in a mongoDB collection. I cannot get a single object returned from mongoDB, but rather the entire user list.

The html, set up using Jade, looks like this:

  //User Login Page
  #login
      h2 User Login
      fieldset
          input#inputUsername(type='text', placeholder='Username')
          button#btnLogin Login
  // /User Login 

And the JavaScript side looks like this:

//Request user credentials on button click
function loginRequest() {
    var userCreds = {
        'username': $('#login fieldset input#inputUsername').val()
    };

    $.getJSON('/users/loginRequest', userCreds, function (data) {
        console.log(data);
    });
}

Which, using Express and Mongoskin, is routed to this:

//GET Login User 
router.get('/loginRequest', function (req, res) {
    var db = req.db;
    db.collection('authorizedUsers').find(req.body).toArray(function (err, items) {
        res.json(items);
    });
})

The issue is I have been unable to correctly pass the specific login information (username) to the GET request. A non-finding request will return all users in the collection and I could search that returned array, but in the case of hundreds of users, that doesn't seem to be the best option. How do I correctly make the GET request using Express routes and Mongoskin?

Thank you.

Upvotes: 0

Views: 6027

Answers (1)

user3998237
user3998237

Reputation:

You should use the findOne method, and pass the input value using name="username", them acess the value in your routes with req.param("username");

Use this code:

Jade:

  #login
      h2  User Login  
        form(role='form', method='get', action='/users/loginRequest')
          input#inputUsername(name='username', type='text', placeholder='Username')

          button#btnLogin(type='submit') Login

And in your route:

  router.get('/loginRequest', function (req, res) {
      var username = req.param("username");

      db.collection('authorizedUsers').findOne(username: username}, function(err, items) {
          if(err) {
              return console.log('findOne error:', err);
          }
          else {
            res.json(items);
          }
      });
  });

Also, this code will protect your sensitive data.

Upvotes: 1

Related Questions