封装增删改查操作,外部只需调用相应接口,返回的数据处理在外部作为回调函数处理
const mongoClient=require('mongodb').MongoClient;
let url="mongodb://localhost:27017"
var _connect=function(callback){
mongoClient.connect(url,(err,db)=>{
if (err) throw err;
callback(db);
})
}
module.exports.insert=function(obj,dbName,collectionName,callback){
_connect(function(db){
if(!Array.isArray(obj)){
obj=[obj];
}
db.db(dbName).collection(collectionName).insertMany(obj,(err,result)=>{
if (err) throw err;
db.close();
callback(result);
})
}
)
}
module.exports.find=function(obj,dbName,collectionName,callback){
_connect(function(db){
db.db(dbName).collection(collectionName).find(obj).toArray((err,result)=>{
if (err) throw err;
db.close();
callback(result);
})
}
)
}
调用查询和插入接口
const ele=require('./common');
let fx=ele.insert;
let fx1=ele.find;
app.get('/login',(req,res)=>{
fx1({user:req.query.user,psw:req.query.psw},'local','userInfo',function(result){
if(result.length!=0){
res.send("登录成功");
}else{
res.status(404).send('用户名或密码错误')
}
})
})
// POST /login gets urlencoded bodies
app.post('/register', urlencodedParser, (req,res)=>{
fx({user:req.body.user,psw:req.body.psw},'local','userInfo',function(result){
if(result.insertedCount!=0){
res.send("注册成功");
}else{
res.status(500).send("注册失败");
}
});
})
app.use('/',express.static('../login'))
app.listen('8989');