首页 > 解决方案 > 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. */ 


    }

});

感谢所有试图帮助我的人!我已经被困在这几个小时了。

标签: javascriptmongodbelectron

解决方案


尝试使用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 }).


推荐阅读