async-awaitを紹介します.nodejsでmongodbを通じてデータベースを操作します.

7109 ワード

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()
})()