【问题标题】:MongoClient's findOne() never resolves on Electron, even when collection is populatedMongoClient 的 findOne() 永远不会在 Electron 上解析,即使填充了集合
【发布时间】: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


【解决方案1】:

尝试使用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中async和sync代码的区别。只是为了了解应该将回调传递给函数的位置,以及您可以在哪里简单地写await Model.method({ options })。

【讨论】:

  • 太棒了,完成这项工作并解决了问题。我将阅读您引用的链接,因为它看起来很有趣。我对同步和异步编程不太熟悉,所以希望我能学到一两件事。
  • @MysteriousEnigma,如果我的回答有帮助,请接受它作为答案,这样它就会关闭已解决的问题或支持它。 (或者你可以两者都做,根据你的意愿)
猜你喜欢
  • 2014-03-17
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
相关资源
最近更新 更多