Skip to content

Instantly share code, notes, and snippets.

@duizendnegen
Created April 8, 2017 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save duizendnegen/a528ce774115be585ccc9943a850ff0f to your computer and use it in GitHub Desktop.
Save duizendnegen/a528ce774115be585ccc9943a850ff0f to your computer and use it in GitHub Desktop.
var MongoClient = require('mongodb').MongoClient;
exports.connect = function(collection, callback) {
MongoClient.connect(process.env.MONGO_CONNECTION_STRING, function(err, db) {
if(err !== null) {
console.error(err);
callback(err);
return;
}
callback(null, db.collection(collection), function() {
db.close();
});
});
}
var MongoStore = require('./mongo-store');
exports.findOrCreate = function(email, callback) {
MongoStore.connect('users', function(err, collection, close) {
if(err !== null) {
close();
callback(err);
return;
}
collection.find({ email: email }).toArray(function(err, docs) {
if(err !== null) {
close();
callback(err);
return;
}
if(docs.length > 1) {
callback("more than one user with the current e-mail found");
} else if(docs.length === 0) {
var doc = {
email: email
};
collection.insert(doc);
callback(null, doc);
} else {
callback(null, docs[0]);
}
close();
});
});
}
exports.find = function(email, callback) {
MongoStore.connect('users', function(err, collection, close) {
if(err !== null) {
close();
callback(err);
return;
}
collection.find({ email: email }).toArray(function(err, docs) {
if(err !== null) {
close();
callback(err);
return;
}
if(docs.length !== 1) {
callback("user not found");
} else {
callback(null, docs[0]);
}
close();
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment