GET user info from MongoDB w/AJAX

- 1 answer

Ad

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) {
    e.preventDefault();
    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;
        if(doc)
            console.log("Found: " + username + ", pass=" + doc.password);
        else
            console.log("Not found: " + username);
        db.close();
    });
    });

  });
});

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!

Ad

Answer

Ad

Use getCollection

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

Ad
source: stackoverflow.com
Ad