微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

复制代码

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐