Can't query mongoDB with mongoose in node.js

前端 未结 4 1941
刺人心
刺人心 2021-01-16 03:28

Suppose I have a collection in my mongoDB: db.co and only have one document:

{ \"_id\" : ObjectId(\"50d083e32cdcf7ce065b616c\"), 
  \"age\" : 22         


        
4条回答
  •  伪装坚强ぢ
    2021-01-16 03:44

    .find() works asynchronous, meaning that its callback runs when your function already has.

    see variable scope in asynchronous function

    //try passing a callback function to your search function, like:
    function findSomeoneInCo (name, callback) {
    
      //happens now - here you could still return something
    
      Co.find({"name": name}, function (err, doc) {
    
       //happens later - too late to return stuff, function has ran already
    
        if (err) {
            callback(err);
            return;
        }
        callback(doc);
      })
    }
    
    
    //call your function passing a callback function
    findSomeoneInCo("lee", function(doc){
      console.log('do something with your results: ' + doc);
    });
    

提交回复
热议问题