介绍一种async-await在nodejs中通过mongodb操作数据库:
个人感觉这种写法特别简单快捷!!
//异步自执行
(async()=>{
const {MongoClient : MongoDB} = require("mongodb");
const client = new MongoDB(
"mongodb://127.0.0.1:27017",
{
useNewUrlParser : true
}
)
let result;
//连接mongodb
result = await client.connect();
//创建数据库people
const db = client.db("people");
//创建集合man
const man = db.collection("man");
//向man集合中添加数据
result = await man.insertMany([{name:"heihie",age:1},{name:"zuoli",age:2},{name:"wangjihao",age:3}])
// console.log(result)
//修改man集合下{age:2}的数据
result = await man.updateMany({age:2},{
$set : {
age:14,
sex:"girl"
}
})
//删除man集合下所有{name:"heihie"}的数据
result = await man.deleteMany({name:"heihie"})
//查看man集合下所有的数据
result = await man.find()
//将man集合下的所有数据以数组的形式输出
console.log(result.toArray((err,doc)=>{
if(err){
throw err
}
console.log(doc)
}))
//关闭数据库(一定不能忘了写!!很重要!!!)
client.close()
})()