javascript - MongoClient的findOne()永远不会在Electron上解析,即使填充了集合

标签 javascript mongodb 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);
    }
});

或者,您需要传递callback,如下所示:
currentCollection.findOne({ country: 'Croatia' }, function (err, doc) {
  if (err) console.error(err);
  console.log(doc);
});
发生这种情况是因为queries are not promises。实际上,我建议您研究node.js中asyncsync代码之间的区别。只是为了了解应将回调传递给函数的位置,以及可以在哪里简单地编写await Model.method({ options })即可。

关于javascript - MongoClient的findOne()永远不会在Electron上解析,即使填充了集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66730396/

相关文章:

mongodb - MapReduce 和 iReport/Jasperserver (MongoDB)?

electron - 不允许拖放到 Electron 应用程序中

angular - 部署/运行: local Express web-server and local client-side angular app that sends ajax requests to this local web-server

javascript - 我可以在 JS 和 PHP 中使用哪个模板引擎?

javascript - 如何将 jQuery 传递给评估代码?

java - MongoDB 唯一索引不起作用

vue.js - 如何使用 Electron js 和 Vue 离线制作桌面应用程序,具有服务器端 Laravel?

javascript 和类 class=input-range 在 ie 中不起作用

javascript - 在javascript中仅返回给定字符串中的数字

python - 使用 python 搜索句子中的术语