NodeJS 如何连接 MongoDB

初始化:

bash 复制代码
yarn init

使用命令:

bash 复制代码
yarn add mongodb

新建 index.js 文件:

js 复制代码
const MongoClient = require('mongodb').MongoClient;
const db_name = "fly_articleDb";
const url = 'mongodb://127.0.0.1:27017';

(async function () {
    const client = new MongoClient(url);

    try {
        // 1. 连接 mongodb 数据库
        await client.connect();
        console.log("连接成功...");
        // 2. 使用数据库fly_articleDb
        const db = client.db(db_name);
        // 3. 通过数据库得到相应的集合test
        const test = db.collection("test");
        // 4. 查询 test 集合中的文档
        const test_list = test.find();
        // 判断是否有文档
        while (await test_list.hasNext()) {
            // 获取该条数据
            const currentData = await test_list.next();
            console.log(currentData);
        }
    } catch (e) {
        console.log(e);
    }
    await client.close();
    console.log("mongodb已关闭...");
})()

这样就能查询 MongoDB 数据库了。

相关推荐
qq_192779875 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272716 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊6 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
tudficdew6 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6527 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
Configure-Handler7 小时前
buildroot System configuration
java·服务器·数据库
2301_821369617 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
电商API_180079052478 小时前
第三方淘宝商品详情 API 全维度调用指南:从技术对接到生产落地
java·大数据·前端·数据库·人工智能·网络爬虫
2401_832131958 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
打工的小王9 小时前
redis(四)搭建哨兵模式:一主二从三哨兵
数据库·redis·缓存