How to get user info from mongodb in node.js

前端 未结 2 2019
轮回少年
轮回少年 2021-01-28 04:44

Totally new to mongo, I\'ve been checking examples for hours, Trying to check if a user exists in this collection:

{ \"name\" : \"chrispy\", \"pass\" : \"xxxx\",         


        
2条回答
  •  悲哀的现实
    2021-01-28 05:41

    Just to be clear, the various database calls are asynchronous actions that utilize Javascript Promises. The call to findOne returns a Promise object, not the found document. That is,

    collection.findOne(
        {name: name}, 
        function(err,doc) { 
          /* handle err or process doc */
        }
    );
    

    is functionally equivalent to

    collection.findOne(
        {name: name}
    ).then(
        // resolved handler
        function(doc) { 
           // process doc 
        }, 
        // rejected handler
        function(err) { 
          // handle err 
        }
    );
    

    Your code was starting the asynchronous findOne call and then closing the database before the call has finished (i.e. the promise resolved or rejected). If you need to close the db, you should do it in the callback, once you've obtained your document.

提交回复
热议问题