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

相关推荐
蓝速科技11 小时前
商用复杂环境翻译机耐用性选型指南丨蓝速科技
大数据·运维·数据库·人工智能·科技
starzy199011 小时前
Flink Sliding Window 详解及代码实现:从窗口重叠到状态爆炸防控
运维·数据库·flink
jnrjian12 小时前
DRG-50857 ORA-30576 drixmd.PurgeKGL CTXSYS
数据库·oracle
志栋智能13 小时前
集成是关键:让巡检超自动化融入现有工具链
运维·服务器·数据库·架构·自动化
IvorySQL13 小时前
PostgreSQL 日报|逻辑解码竞态条件修复(9 月 20 日)
数据库·人工智能·postgresql
adinnet202614 小时前
为什么 RAG 需要 Milvus?向量数据库到底存了什么
大数据·数据库
Elastic 中国社区官方博客14 小时前
使用 Elasticsearch 和 Jina 进行 AI 视频搜索:精准找到你需要的视频片段秒数
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
Omics Pro15 小时前
新型条件传输模型!虚拟细胞扰动预测
数据库·人工智能·算法·机器学习·自然语言处理
实验室管理云平台15 小时前
环境检测实验室管理系统:提升效率与数据准确性的关键工具
大数据·数据库·科技
SelectDB技术团队15 小时前
快手基于 Apache Doris 千亿多模态检索的实践
数据库·数据分析·全文检索·快手·apache doris·向量索引·多模态检索