【发布时间】:2021-04-27 19:22:04
【问题描述】:
我对 Node.js 的 MongoDB 驱动程序的异步实现有点问题。
在文档示例中,连接发生如下:
const client = new MongoClient(uri, ...);
async function run() {
try {
await client.connect();
const coll = client.db('locations').collection('streets');
coll.find({...});
} catch {
...
} finally {
client.close();
}
}
run().catch(console.dir);
但是假设我想在对象中使用连接,而不是在需要连接时为每种情况创建一个函数。例如,我想创建一个允许我将 cmets 插入数据库的对象:
const Comments = {
connection: /* how would I put a MongoDB connection here when it's async? */,
commentsCollectionRef: /* how would I put a collection reference here? */
add: function(user, comment) {
collectionRef.insertOne({user, comment});
}
};
/* And to use the object like this to insert comments: */
Comment.add("Martin", "hello");
Comment.add("Julie", "hi");
Comment.add("Mary", "hello");
想必,这样的事情是不可能的:
async function connect() {
await client.connect();
}
const Comments = {
connection: connect() /* this returns a promise, but you can't store a reference to its value like this */
...
}
拥有一个每次连接并关闭连接的功能真的是 MongoDB 的唯一选择吗?
谢谢
【问题讨论】:
标签: javascript node.js mongodb asynchronous nosql