首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Node.js 连接 MongoDB--Promise

Node.js 连接 MongoDB--Promise

原创
作者头像
陈不成i
修改于 2021-07-13 14:40:06
修改于 2021-07-13 14:40:06
1.7K0
举报
文章被收录于专栏:ops技术分享ops技术分享

使用 Promise

Promise 是一个 ECMAScript 6 提供的类,目的是更加优雅地书写复杂的异步任务。

如果你还不了解 Promise,可以参考 JavaScript Promise。

以下实例使用 Promise 创建集合:

代码语言:javascript
复制
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/runoob";
MongoClient.connect(url).then((conn) => {
    console.log("数据库已连接");
    var dbase = conn.db("runoob");
    dbase.createCollection("site").then((res) => {
        console.log("已创建集合");
    }).catch((err) => {
        console.log("数据库操作错误");
    }).finally(() => {
        conn.close();
    });
}).catch((err) => {
    console.log("数据库连接失败");
});

Promise 数据操作

现在我们在一个程序中实现四个连续操作:增加 、查询 、更改 、删除。

代码语言:javascript
复制
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/";
MongoClient.connect(url).then((conn) => {
    console.log("数据库已连接");
    const test = conn.db("testdb").collection("test");
    // 增加
    test.insertOne({ "site": "runoob.com" }).then((res) => {
        // 查询
        return test.find().toArray().then((arr) => {
            console.log(arr);
        });
    }).then(() => {
        // 更改
        return test.updateMany({ "site": "runoob.com" },
            { $set: { "site": "example.com" } });
    }).then((res) => {
        // 查询
        return test.find().toArray().then((arr) => {
            console.log(arr);
        });
    }).then(() => {
        // 删除
        return test.deleteMany({ "site": "example.com" });
    }).then((res) => {
        // 查询
        return test.find().toArray().then((arr) => {
            console.log(arr);
        });
    }).catch((err) => {
        console.log("数据操作失败" + err.message);
    }).finally(() => {
        conn.close();
    });
}).catch((err) => {
    console.log("数据库连接失败");
});

执行结果:

代码语言:javascript
复制
数据库已连接
[ { _id: 5f1664966833e531d83d3ac6, site: 'runoob.com' } ]
[ { _id: 5f1664966833e531d83d3ac6, site: 'example.com' } ]
[]

用异步函数实现相同的数据操作

代码语言:javascript
复制
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://localhost/";
 
async function dataOperate() {
    var conn = null;
    try {
        conn = await MongoClient.connect(url);
        console.log("数据库已连接");
        const test = conn.db("testdb").collection("test");
        // 增加
        await test.insertOne({ "site": "runoob.com" });
        // 查询
        var arr = await test.find().toArray();
        console.log(arr);
        // 更改
        await test.updateMany({ "site": "runoob.com" },
            { $set: { "site": "example.com" } });
        // 查询
        arr = await test.find().toArray();
        console.log(arr);
        // 删除
        await test.deleteMany({ "site": "example.com" });
        // 查询
        arr = await test.find().toArray();
        console.log(arr);
    } catch (err) {
        console.log("错误:" + err.message);
    } finally {
        if (conn != null) conn.close();
    }
}
 
dataOperate();

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 使用 Promise
    • Promise 数据操作
    • 用异步函数实现相同的数据操作
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档