I'm very new to Nodejs and i'm trying to find a record in my db(mongo) by submitting a code and crosschecking the record to see if it exists.
I'm not really clear on how to approach this to get to an endresult stating "There is a code, please continue" and "There is no code".
This is what i have so far as a result of my fiddling:
userProvider.js:
UserProvider.prototype.findByCode = function(code, callback) {
this.getCollection(function(error, user_collection) {
user_collection.findOne({code: code}, function(error, result) {
callback(error, result)
});
});
}
The get collection belonging to userProvider.js:
UserProvider.prototype.getCollection= function(callback) {
this.db.collection('users', function(error, user_collection) {
if( error ) callback(error);
else callback(null, user_collection);
});
};
app.js:
app.post('/game/code', function(req, res) {
if (req.param('code')) {
userProvider.findByCode(req.param('code'), function(error, result) {
console.log(error);
console.log(result);
});
}
});
And the jade form submitting the code:
extends layout
block content
h1= "Gimme a code"
div
form( method="post")
div
div
span.label code :
input(type="text", name="code", id="code")
div
input(type="submit", value="Verbind")
Console logging the param('code') results in the code. So i'm pretty sure that one's solid. So why's there a null returned?
From the question, you didn't say where the 'null' was returned. I am new to nodejs as well, however I noticed in your code:
app.post('/game/code', function(req, res) {
if (req.param('code')) {
userProvider.findByCode(req.param('code'), function(error, result) {
console.log(error);
console.log(result);
});
}
});
and you didn't call the 'res' object. You should try something like this:
app.post('/game/code', function(req, res) {
if (req.param('code')) {
userProvider.findByCode(req.param('code'), function(error, result) {
if(error)
res.send(404, 'There is no code');
else {
console.log(result);
res.send('There is a code:'+result);
}
});
}
});
Check out http://expressjs.com/api.html#res.status for various things you do with res object