封装mongodb增删改查

封装增删改查操作,外部只需调用相应接口,返回的数据处理在外部作为回调函数处理

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');

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值