我尝试使用Node.js,Express和Mongodb构建REST API。我使用mongodb npm包连接数据库,下面是我的sever.js文件代码
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var port = process.env.PORT || 8080;
var mongo = require("mongodb");
var Server = mongo.Server;
var Db = mongo.Db;
var ObjectID = mongo.ObjectID;
try{
var config = require('./configure.js');
}catch(e){
console.log("configuration file is hidden on github for security");
config = null;
}
var usersCollection = config.usersCollection;
var login = require('./routes/login/index.js');
var signup = require('./routes/signup/index.js');
var Database = new Db(process.env.DBNAME || config.DBNAME , new Server(process.env.DBHOST || config.DBHOST, process.env.DBPORT || config.DBPORT, {'native_parser': true}));
Database.open(function (err, mongoclient) {
if(err){
console.log("Failed to connect to the database. Please Check the connection");
throw err;
}else{
Database.authenticate(process.env.DBUSER || config.DBUSER, process.env.DBPASS || config.DBPASS, function(err, res) {
if (err) {
console.log("Authentication Failed");
throw err;
}else{
console.log("Connected to the database Successfully");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var users = Database.collection(usersCollection);
login(app,users);
signup(app,users);
Database.close();
}
});
}
});
app.listen(port,function(){
console.log("Server Started Listening to port : "+port);
});
路由/登录/ index.js
module.exports = function(app,users){
app.route('/login')
.post(function(req,res){
var username = req.body.username;
var password = req.body.password;
var query = {'FirstName':username};
users.find().toArray(function(err,docs){
if(err){
throw err;
}else{
console.log("no err");
if(doc.LastName == password){
res.send({status : true});
}else{
res.send({status : false});
}
}
});
});
}
和routes / signup / index.js
module.exports = function(app,users){
app.route('/signup')
.post(function(req,res){
var doc = { EmpNo:"1",
FirstName:"Andrew",
LastName:"Neil",
Age:"30",
Gender:"Male",
Skill:"MongoDB",
Phone:"408-1234567",
Email:"Andrew.Neil@gmail.com",
Salary:"80000"
};
users.insert(doc,function(err,info){
if(err){
throw err;
}else{
console.log('Successfully inserted ' + JSON.stringify(info));
res.send({result: 'done'});
}
});
});
}
当我试图在server.js中插入文档时,我能够成功插入它们但是通过routes / signup / index.js我得到的实例池被破坏了类似的如果我尝试在server.js中找到文件没有错误但是如果我尝试从routes / login / index.js那样做,那么当拓扑被破坏时我会收到错误。
需要帮助来解决它。
答案 0 :(得分:4)
如果在进程中间以某种方式切断连接,则抛出这些错误。
因为users.find()
和users.insert()
函数都是异步的,所以server.js文件到达Database.close()
函数并在完成进程之前关闭与数据库的连接,从而产生错误。