mongodb连接数据库的基本操作

//进行以下操作时,先安装mongodb模块

cnpm install mongodb -S

//从mongodb里边获取MongoClient(客户端)

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

//定义连接的数据库

const db_name = "name" ;

//定义连接的数据库中的表格

const db_collection = "studenss" ;

打开数据库以后操作

mongoClient.connect(data_url,(err,client) => {
    //MongoClient(客户端)连接数据库地址
    if(err) throw new Error(err) ;
        //如果异常则抛出异常

    const collection = client.db(db_name).collection(db_collection) ;
                         //连接数据库    和    连接数据库中的表
        //collection就是数据库中的表(BK1910.studenss)

//增  	删	改	查


})

//所有的增删改查 都需要在MongoClient(客户端)连接数据库地址成功后的回调函数内填写(也就是在上边空出来的位置中填写)

    //增
    collection.save({ username: "aaa", password: "111" }, (err, result) => {
        if (err) throw new Error(err);
        client.close();
    });

    //删
    // collection.remove({username:"aaa"} , (err) => {
    //     client.close() ;
    // })

    //改
    collection.update({ name: "钱九九" }, { $set: { name: "钱十" } }, (err, result) => {
        client.close();
    }, false, true);

    //查
    collection.find().toArray((err, result) => {
        console.log(result);
    })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值