【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.updata(
        {
            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().toArrat((err,result)=>{
        console.log(result);
        client.close();
    })
})

猜你喜欢

转载自www.cnblogs.com/nanianqiming/p/9080906.html