Totally new to mongo, I\'ve been checking examples for hours, Trying to check if a user exists in this collection:
{ \"name\" : \"chrispy\", \"pass\" : \"xxxx\",
So here are the changes before it started to work, removed var Doc = , and closed the db only after function within findOne() is fired, else it closes the DB before the result.
var name = 'chrispy';
var pass = '';
console.log("About to check for name and pw");
Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db) {
if(err) throw err;
var collection = db.collection('users');
// does user exist
collection.findOne({name : name}, function(err,doc){
if(err) throw err;
if(doc)
console.log("Found: "+name+", pass="+doc.pass);
else
console.log("Not found: "+name);
db.close();
});
});
Just to be clear, the various database calls are asynchronous actions that utilize Javascript Promises. The call to findOne returns a Promise object, not the found document. That is,
collection.findOne(
{name: name},
function(err,doc) {
/* handle err or process doc */
}
);
is functionally equivalent to
collection.findOne(
{name: name}
).then(
// resolved handler
function(doc) {
// process doc
},
// rejected handler
function(err) {
// handle err
}
);
Your code was starting the asynchronous findOne call and then closing the database before the call has finished (i.e. the promise resolved or rejected). If you need to close the db, you should do it in the callback, once you've obtained your document.