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 数据库了。

相关推荐
这个DBA有点耶2 小时前
2026年分布式数据库有哪些主流选择?先评估这5个维度再决定
数据库·分布式·dba
这个DBA有点耶5 小时前
从MySQL 5.7到8.0:JSON查询性能差在哪?虚拟列索引vs多值索引怎么选
数据库·mysql·架构
胡写代码5 小时前
数据库审计字段,别再每张表各写一套了——我统一成这 6 个字段
数据库
SelectDB9 小时前
为什么 JSON 正在成为分析数据库新的竞争点?
数据库·json·agent
ClouGence10 小时前
开源数据库管理工具 CloudDM 4.2.0 发布,新增 GoldenDB、KingbaseES 等数据源
数据库·dba·devops
发霉的馒头10 小时前
ORA-00845: MEMORY_TARGET not supported on this system的解决方法
数据库
草莓熊Lotso12 小时前
【Redis 初阶】Set 类型深度解析:去重集合的运算能力与实战场景
linux·网络·数据库·windows·redis·tcp/ip·缓存
煎饼皮皮侠13 小时前
【设计】设计一个web版的数据库管理平台后端(之五) --借鉴mybatis
数据库·mybatis
东风破_20 小时前
danci 2:创建的单词书到底存在哪里?从 Supabase 一路理解 ORM、Drizzle 和 RLS
数据库·后端·node.js
橙子家21 小时前
OSS 文件上传的几个风险点和解决方案
数据库