javascript - MongoClient 的 findOne() 永远不会在 Electron 上解析,即使填充了集合
问题描述
我正在使用 Electron 制作一个 Web 应用程序,并且成功连接到 Mongo DB Atlas 数据库,并且能够向它发送信息。但是,我似乎无法检索它。我包含的第一段代码是我连接到数据库的方式。
MongoClient.connect(URI, (err, client) => {
if (err){
console.log("Something unexpected happened connecting to MongoDB Atlas...");
}
console.log("Connected to MongoDB Atlas...");
currentDatabase = client.db('JukeBox-Jam-DB'); /* currentDatabase contains a Db */
});
然后,这第二个片段是我一直在写入数据库的方式,它似乎工作得很好。
ipc.on('addUserToDatabase', (event, currentUser) => {
const myOptions = {
type: 'info',
buttons: ['Continue'],
defaultId: 0,
title: 'Success',
message: 'Your account has been created.'
};
dialog.showMessageBox(mainWindow, myOptions);
currentCollection = currentDatabase.collection('UsersInformation');
currentCollection.insertOne(currentUser);
});
最后,这是我一直试图用来从数据库中检索信息的代码。我看不出我可能在哪里犯了错误,因此它不适用于检索,但可以用于写作。据我了解, findOne() 在不带参数传递时应该简单地返回一个 Promise,该 Promise 解析为与传递给它的查询匹配的第一个条目。如果未提供查询,则它将解析为首先放入数据库的项目。如果没有与查询匹配的条目,那么它应该解析为 null。任何想法为什么这不起作用?
ipc.on('checkUsernameRegistration', (event) => {
currentCollection = currentDatabase.collection('UsersInformation');
let myDocument = currentCollection.findOne(); /* I don't understand why this isn't working! */
console.log(myDocument); /* This prints Promise { <pending> } */
if (myDocument !== null){ /* If myDocument is not null, that means that that there is already someone with that username in the DB. */
}
});
感谢所有试图帮助我的人!我已经被困在这几个小时了。
解决方案
尝试使用async/await
:
ipc.on('checkUsernameRegistration', async (event) => {
currentCollection = currentDatabase.collection('UsersInformation');
let myDocument = await currentCollection.findOne({ _id: value });
if (myDocument !== null){
console.log(myDocument);
}
});
或者,您需要传递 a callback
,如下所示:
currentCollection.findOne({ country: 'Croatia' }, function (err, doc) {
if (err) console.error(err);
console.log(doc);
});
发生这种情况是因为查询不是承诺。实际上,我建议您研究一下node.jsasync
和code之间的区别。sync
只是为了了解应该将回调传递给函数的位置,以及您可以在哪里简单地编写await Model.method({ options })
.
推荐阅读
- freemarker - 如何在freemarker语言中将当前日期格式(YYYY-MM-DD HH:MM:SS)转换为(YYMMDD)格式
- firebase - Firebase 事务触发函数错误?
- javascript - 由于 MIME 类型 ('') 在 apache karaf 中部署的 servlet Web 应用程序中不可执行而出现错误
- java - 这些关于插入排序的代码之间的比较是什么?
- matlab - MATLAB 将 Live Script 导出为 pdf 并显示行号?
- android - 使用 microsoft-cognitive 缩略图生成从 Android 手机返回带有照片的不可用文件
- javascript - 如何使用 php 在我的登录时实现 cookie"
- ffmpeg - 如何使用 ffmpeg 将多个视频转换为一个图像序列?
- ssrs-2012 - 如何在组上的 SSRS 中的每一页上重复行组标题
- java - 强制属性在杰克逊中序列化为身份