GET user info from MongoDB w/AJAX

- 1 answer


I've spent a few hours looking around on Stack Overflow, but I can't find too many articles that help me with my problem. Still a bit new to MongoDB.

Basically, I am trying to get the login portion of my website running. I already have a database in MongoDB with a collection called "accounts" with one sample user that looks like this:

> db.accounts.findOne()
    "_id" : ObjectId("5675e90bcb76f3710ff2d0d1"),
    "username" : "jose",
    "password" : "8943",
    "email" : "[email protected]",
    "__v" : 0

On my login page, I collect both the username and password (assuming the user has already registered), store those in variables and use the following code to check if the user exists. This code is based on the answer from this other Stack Overflow article.

var mongoose = require('mongoose');

$(function() {
  $('#login').on('click', function(e) {
    var username = $('#name').val();
    var password = $('#password').val();

    console.log("About to check for name and pw");
    mongoose.connect('mongodb://localhost/MyDataBase', function(err, db) {
    if(err) throw err;
    var collection = db.collection('accounts');

    // does user exist
    collection.findOne({username : username}, function(err, doc){
        if(err) throw err;
            console.log("Found: " + username + ", pass=" + doc.password);
            console.log("Not found: " + username);


EDIT: The first console.log runs: "About to check for name and pw". Then I get the error, "required is not defined". Am I mixing server-side JS with client-side? I have mongoose required in my server.js file as well...can I perform a module.export to be able to use mongoose in this current file to connect to the database?

Thank you in advance!




Use getCollection

var collection = db.getCollection('accounts');