【发布时间】:2021-06-18 04:10:27
【问题描述】:
我正在使用 Electron 制作一个 Web 应用程序,并且我成功连接到 Mongo DB Atlas 数据库,并且能够向它发送信息。但是,我似乎无法检索它。我包含的第一个 sn-p 代码是我连接到数据库的方式。
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 */
});
然后,第二个 sn-p 是我一直在写入数据库的方式,它似乎工作得非常好。
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. */
}
});
感谢所有试图帮助我的人!我已经被困了几个小时了。
【问题讨论】:
标签: javascript mongodb electron