Wednesday, 12 November 2014

using username and password with the native mongoDB nodejs driver (authentication)

By using the native nodejs mongoDB driver:


After your mongodb has authentication, you should set username and password. so it used to be like this:



mongodb.open(function(err, db) {
if (err) {
return callback(err);
}

//load all posts from db
db.collection('posts', function(err, collection) {
if (err) {
mongodb.close();
return callback(err);
}
//insert new post
collection.insert(post, {
safe : true
}, function(err) {
mongodb.close();
if (err) {
return callback(err);//if failed return err
}
callback(null);//return err : null
});
});
});

you can get the collection after you have the db opened.

However, if you have authentication, you should send a authenticate request and do collection after the authentication checking past.:


mongodb.open(function(err, db) {
if (err) {
return callback(err);
}

db.authenticate(settings.dbusername, settings.dbpassword, function(
autherr, result) {
if (autherr) {
return callback(autherr);
}
//load all posts from db
db.collection('posts', function(err, collection) {
if (err) {
mongodb.close();
return callback(err);
}
//insert new post
collection.insert(post, {
safe : true
}, function(err) {
mongodb.close();
if (err) {
return callback(err);//if failed return err
}
callback(null);//return err : null
});
});
});
});



No comments:

Post a comment