有两种不同的方法可以做到这一点
#1
Documentation(注意文档中的示例使用Db对象)
// Your code from the question
// Listen for when the mongoclient is connected
mongoclient.open(function(err, mongoclient) {
// Then select a database
var db = mongoclient.db("exampledatabase");
// Then you can authorize your self
db.authenticate('username', 'password', function(err, result) {
// On authorized result=true
// Not authorized result=false
// If authorized you can use the database in the db variable
});
});
#2
Documentation MongoClient.connect
Documentation The URL
A way I like much more because it is smaller and easier to read.
// Just this code nothing more
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://username:password@localhost:27017/exampledatabase", function(err, db) {
// Now you can use the database in the db variable
});