0

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: username, 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?

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

4 Comments

The problem is that I have a Server.js file that calls the getUserType function in de Database.js file. The thing is that I dont know how to get the value from de database.js to the server.js.
You should pass a callback function into findOne from Server.js directly. It's difficult to pass variables around the way you are suggesting as MongoDB is not synchronous. I would suggest not encapsulating findOne in database.js, as MongoDB was based around the best practice for dealing with callbacks (that is, you pass a callback into findOne in the exact location it is called). That said, you can always loop through a callback by encapsulating and passing the callback through in database.js. Does that make sense?
it does :D I will just put the findOne function in the server and run it like that. I just thought i would seperate de database with the server so everything looks a little bit ordered.
Yeah, MongoDB doesn't specifically lend itself to this encapsulation concept. I've edited my response to give you an idea of what this would feel like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.