[英]Error acessing mongo collection using mongo client asynchronously
我已經構建了以下 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!");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.