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

相关推荐
belldeep24 分钟前
本草纲目:如何应用 PostgreSQL 实现【中医药】主题数据库 ?
数据库·postgresql·本草纲目
Bert.Cai36 分钟前
MySQL CURTIME()函数详解
数据库·mysql
Bert.Cai36 分钟前
MySQL CURDATE()函数详解
数据库·mysql
NGSI vimp1 小时前
MySQL|MySQL 中 `DATE_FORMAT()` 函数的使用
数据库·mysql
HAWK eoni1 小时前
Mysql 驱动程序
数据库·mysql
二哈赛车手1 小时前
新人笔记---实现简易版的rag的bm25检索(利用ES),以及RAG上传时的ES与向量数据库双写
java·数据库·笔记·spring·elasticsearch·ai
何中应1 小时前
CentOS 7安装、卸载MySQL数据库(二)
数据库·mysql·centos
KmSH8umpK2 小时前
Redis分布式锁从原生手写到Redisson高阶落地,附线上死锁复盘优化方案进阶第六篇
数据库·redis·分布式
梁萌2 小时前
mysql使用事件做日志表数据转移
数据库·mysql
lThE ANDE2 小时前
MySQL中的TRUNCATE TABLE命令
数据库·mysql