node+mongodb之async、await

const mongodb = require("mongodb");
const mongoClient = mongodb.MongoClient;

async function _connect(){
    return await new Promise(resolve =>{
    	mongoClient.connect("mongodb://127.0.0.1:27017",{useNewUrlParser:true},function(err,client){
	        resolve(client.db("test"));//库名
	    });
	})
}
//查找符合条件的一条记录 coll集合名
module.exports.findOne = async function(coll,whereObj){
	var db = await _connect()
	return await new Promise(resolve =>{
    	db.collection(coll).findOne(whereObj,function(err,result){
			resolve({err,result})
		});
	})
}

//根据id查找一条记录
module.exports.findOneById = async function(coll,id){
	var db = await _connect()
	return await new Promise(resolve =>{
		db.collection(coll).findOne({_id : mongodb.ObjectId(id)},function(err,result){
			resolve({err,result})
		});
	})
}

//插入一条记录
module.exports.insertOne = async function(coll,obj){
	var db = await _connect()
	return await new Promise(resolve =>{
		db.collection(coll).insertOne(obj,function(err,result){
			resolve({err,result})
		});
	})
}

//查找多条符合条件的记录
module.exports.find = async function(coll,obj){
    obj.whereObj = obj.whereObj || {};
    obj.sortObj = obj.sortObj || {};
    obj.limitNum = obj.limitNum || 0;
    obj.skipNum = obj.skipNum || 0;
    var db = await _connect()
    return await new Promise(resolve =>{
    	db.collection(coll).find(obj.whereObj).sort(obj.sortObj).limit(obj.limitNum).skip(obj.skipNum).toArray(function(err,result){
			resolve({err,result})
		});
	})
}

//通过指定的id删除单条记录
module.exports.deleteOneById = async function(coll,id){
	var db = await _connect()
	return await new Promise(resolve =>{
	db.collection(coll).deleteOne({_id : mongodb.ObjectId(id)},function(err,result){
			resolve({err,result})
		});
	})
}

//删除多条记录
module.exports.delete = async function(coll,obj){
	var db = await _connect()
	return await new Promise(resolve =>{
		db.collection(coll).deleteMany(obj,function(err,result){
			resolve({err,result})
		});
	})
}

//修改信息
module.exports.updateOne = async function(coll,id,obj){
	var db = await _connect()
	return await new Promise(resolve =>{
		db.collection(coll).updateOne({_id : mongodb.ObjectId(id)},obj,function(err,result){
			resolve({err,result})
		});
	})
}

//查询总条数
module.exports.count = async function(coll,whereObj){
	var db = await _connect()
	return await new Promise(resolve =>{
		db.collection(coll).countDocuments(whereObj).then(function(err,result){
			resolve({err,result})
		});
	})
}

使用示例

const mongodb2 = require('../db2.js');
var login = async (ctx, next) => {
	var data = await 
 	mongodb2.findOneById("users","5c678ee83a4b151a3d560c44");
  	ctx.response.body = {
  		data
  	};
};

module.exports = login;

你可能感兴趣的:(node,数据库,mongodb,node)