javascript - 使用 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
?
解决方案
异步函数返回一个承诺而不是解析的数据。
这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!");
}
}
推荐阅读
- flutter - 后帧回调 - 循环
- r - 在 r shiny 中绘制单选按钮时找不到错误对象
- flask - SQL Alchemy AttributeError:“str”对象没有属性“_sa_instance_state”
- c# - 在多线程应用程序中同步属性值的正确方法
- oracle - ORACLE SQL DEVELOPER-select count(*) from multiple databases
- just-audio - MediaState 流 ConnectionState 保持等待 - audio_service 颤动
- python - 根据序列号和故障标签定义故障范围
- excel - 在 Excel 中使用宏自动求解
- javascript - 如果我调用它的方法,我的类将返回 undefined
- python - 为什么我的文本文件的内容没有在 python 中打印?