【node】node连接mongodb操作数据库

1、下载第三方模块mongodb

cnpm install mongodb --save

2、检测是否连接成功

复制代码
1、引入第三方模块mongodb并创建一个客户端

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

2、连接数据库
//连接地址
const url = "mongodb://127.0.0.1:27017";

//连接数据库的名称
const db_name = "test";

//检测是否连接成功
MongoClient.connect(url,(err,client)=>{
    console.log(err,client);
})
复制代码

3、连接数据库并选用数据库中的哪张表

复制代码
const MongoClient = require("mongodb").MongoClient;
 
const url = "mongodb://127.0.0.1:27017";
 
const db_name = "test";
 
MongoClient.connect(url,(err,client)=>{
 
    //连接db_name这个数据库并使用student这张表
    const collection = client.db(db_name).collection('student');
})
复制代码

 

4、增

复制代码
//引入第三方模块mongodb并创建一个客户端
const MongoClient = require("mongodb").MongoClient;

//定义连接的地址
const url = "mongodb://127.0.0.1";

//定义连接的数据库
const db_name = "test";

//客户端连接数据库
MongoClient.connect(url,(err,client)=>{
    //连接db_name这个数据库并使用student这个表
    const collection = client.db(db_name).collection("student");
    
    //存入数据并退出连接
    collection.save(
        {
            name:"德玛西亚",
            age:25,
            sex:"男"
        },
        (err,result)=>{
            client.close();
        }
    )
})

复制代码

 

5、删

复制代码
//引入第三方模块mongodb并创建一个客户端
const MongoClient = require("mongodb").Mongoclient;

//定义连接的地址
const url = "mongodb://127.0.0.1:27017";

//定义连接的数据库
const db_name = "test";

//客户端连接数据库
MongoClient.connect(url,(err,client)=>{
    //连接db_name这个数据库并使用student这个表
    const collection = client.db(db_name).collection("student");
    
    //删除指定数据并退出连接
    collection.remove(
        {
            name:"德玛西亚"
        },
        (err,result)=>{
            client.close();
        }
    )
})

复制代码

6、改

复制代码
//引入第三方模块mongodb并创建一个客户端
const MongoClient = require("mongodb").MongoClient;

//定义连接的地址
const url = "mongodb://127.0.0.1:27017";

//定义连接的数据库
const db_name = "test";

//客户端连接数据库
MongoClient.connect(url,(err,client)=>{

     //连接db_name这个数据库并使用student这个表
    const collection = client.db(db_name).collection("student");
    
    //更新指定数据并退出连接
    collection.update(
        {
            name:"德玛西亚"
        },
        {
            $set:{name:"提莫队长"}
        }
        (err,result)=>{
            client.close();
        }
    )
})

复制代码

7、查

复制代码

//引入第三方模块mongodb并创建一个客户端 const MongoClient = require("mongodb").MongoClient; //定义连接的地址 const url = "mongodb://127.0.0.1:27017"; //定义连接的数据库 const db_name = "test"; //客户端连接数据库 MongoClient.connect(url,(err,client)=>{ //连接db_name这个数据库并使用student这个表 const collection = client.db(db_name).collection("student"); //查找到所有数据并转化成一个数组 collection.find().toArray((err,result)=>{ console.log(result); client.close(); }) })

复制代码

原文地址:https://www.cnblogs.com/donve/p/10265094.html