Error: db object already connecting, open cannot be called multiple times
我不知道哪里出了问题,这是node.js实战第一章出现的问题
这是db.js var settings = require(‘…/settings’), Db = require(‘mongodb’).Db, Connection = require(‘mongodb’).Connection, Server = require(‘mongodb’).Server; module.exports = new Db(settings.db, new Server(settings.host, Connection.DEFAULT_PORT),{safe: true});
这是user.js var mongodb = require(‘./db’);
function User(user){ this.name = user.name; this.password = user.password; this.email = user.email; };
module.exports = User;
User.prototype.save = function(callback){ var user = { name: this.name, password: this.password, email: this.email };
mongodb.open(function(err, db){
if (err){
mongodb.close();
return callback(err);
}
db.collection('users',function(err, collection){
if (err){
mongodb.close();
return callback(err);
}
collection.insert(user, {
safe: true
}, function(err, user){
mongodb.close();
if (err){
return callback(err);
}
callback(null, user[0]);
});
});
});
};
User.get = function(name, callback){ mongodb.open(function(err,db){ if (err){ return callback(err); } db.collection('users’, function (err, collection) { if (err) { mongodb.close(); return callback(err); } collection.findOne({ name: name },function (err,user) { if (err) { return callback(err) } callback(null,user); }); }); }); };