开发者

Store data from MongoDB in variable - mongoose and node.js

开发者 https://www.devze.com 2023-03-28 03:19 出处:网络
I was wondering if someone could show me how to get a string value from mongodb and store that in a variable.

I was wondering if someone could show me how to get a string value from mongodb and store that in a variable.

db.model("users").findOne({username: u开发者_如何转开发sername, password: password}, {type:1}, 
    function(err, data) {
        if(err) {
            return "Error";
        } else if() {
            return "No records";
        } else {
            return data.type;
        }
    }
);

I get the type value when I run this.

But how do I store this in a variable outside this function?


The return value from your anonymous function is completely ignored. You can store the variable anywhere that is accessible from your current scope. E.g.

var Database = function {
  var myText = null;

  return {    

    getUser: function(username, password, callback) {
      db.model("users").findOne({username: username, password: password}, {type:1},
           function(err, data) {
             if (err) {
               myText = "Error";
             }
             else if (data.length == 0) {
               myText = "No records";
             }
             else {
               myText = data.type
             }

             $('.log').html(myText);
             callback(myText);
      });
    };
  };
}();

From server.js, you could then call:

Database.getUser(username, password, function(theText) { alert(theText); });

You will need to be clever about how different elements interact since Javascript with callbacks does not run synchronously. That said, it should be possible to achieve any result you are looking for. Enjoy and happy coding!

0

精彩评论

暂无评论...
验证码 换一张
取 消