Reputation: 343
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?
Upvotes: 0
Views: 5333
Reputation: 9086
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!
Upvotes: 2