首页 > 解决方案 > 使用 mongo 客户端异步访问 mongo 集合时出错

问题描述

我已经构建了以下 mongo 客户端访问引导文件:

import { MongoClient } from "mongodb";

let db = null;

// Connect to mongo
const uri = "mongodb://localhost/mydb";
const opts = { useUnifiedTopology: true };

const connect = async () => {
    console.log("Connecting to database...");

    let client = await MongoClient.connect(uri, opts).catch(error => {
        console.log("Error connecting to database: " + err);
    });

    if (client) {
        console.log("Database connected.");
        db = client.db("mydb");
    }

    return client;
};

// Get database connection
const getDb = async () => {
    if (!db) await connect();

    return db;
};

// Get Collection
const getCollection = async name => {
    let database = await getDb();

    let collection = await database.collection(name);

    if (!collection)
        throw new Error("(mongo) Cannot get collection named " + name);

    return collection;
};

export { db, getCollection };

当尝试在另一个程序中第一次访问该集合时:

import { getCollection } from "./mongoutils";

const init = async () => {
    let user = await getCollection("users").findOne({ name: "Josh"});

    console.log("User found!");
}

我收到以下错误:

UnhandledPromiseRejectionWarning: TypeError: (0 , _mongo.getCollection)(...).findOne is not a function

我怎样才能正确修复这个错误,保持整个结构async/await

标签: javascriptmongodbasynchronous

解决方案


异步函数返回一个承诺而不是解析的数据。

getCollection()是一个异步函数。因此,调用getCollection("users")将返回一个承诺,而不是返回的已解决集合本身,因为我推测您所期望的。正确的做法是:

import { getCollection } from "./mongoutils";

const init = async () => {
    let userCollection = await getCollection("users");
    try {
      let user = await userCollection.findOne({ name: "Josh"})
      console.log("User found!");
    } catch (e) { 
      console.log("User not found!");
    }
}

推荐阅读