npm init -y(初始化项目)

npm install mongodb --save(引入MongoDB)

const { MongoClient } = require("mongodb");  //依赖MongoClient

let client=new MongoClient("mongodb://127.0.0.1:27017");  //实例化一个客户端

//添加一条数据
async function run(){
    try{
        let db=await client.db("数据库名称");  //获取数据库
        let students=await db.collection("表名");  //获取集合,表
        let doc={id:202201,name:"tom",age:19};  //将添加的数据对象
        let result=await students.insertOne(doc);  //执行向数据库中添加数据并等待响应结果
        console.log(result);
    }
    finally{
        await client.close();  //关闭数据库
    }
}

run().catch(console.log);

 

posted on 2022-09-19 11:59  最帅爸爸  阅读(51)  评论(0)    收藏  举报