How to get user info from mongodb in node.js

前端 未结 2 1996
轮回少年
轮回少年 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:21

    So here are the changes before it started to work, removed var Doc = , and closed the db only after function within findOne() is fired, else it closes the DB before the result.

    var name = 'chrispy';
    var pass = '';
    
    console.log("About to check for name and pw");
    Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db) {
    if(err) throw err;
    var collection = db.collection('users');
    
    // does user exist
    collection.findOne({name : name}, function(err,doc){
        if(err) throw err;
        if(doc)
            console.log("Found: "+name+", pass="+doc.pass);
        else
            console.log("Not found: "+name);
        db.close();
    });
    

    });

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题