NodeJS 如何连接 MongoDB

初始化:

yarn init

使用命令:

yarn add mongodb

新建 index.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 数据库了。

posted @ 2023-10-03 12:05  辰梦starDream  阅读(3)  评论(0编辑  收藏  举报  来源