My college course just started going over mongodb and we have an assignment to work on. Everything seems to be going well so far, but I have ran into an issue returning a value in my response.write. Scope issues seem to always be the ones that plague me. Here is the code:
var querystring = require("querystring"),
fs = require("fs"),
mongodb = require('mongodb'),
server = new mongodb.Server('localhost',27017, {auto_reconnect: true}),
db = new mongodb.Db('testdb',server);
db.createCollection('testCollection', {safe : true}, function(err, collection){});
function createData(response, postData) {
var fname = querystring.parse(postData).fname;
var lname = querystring.parse(postData).lname;
var phone = querystring.parse(postData).phone;
var info = {'fname':fname,'lname':lname,'phone':phone};
var infojson = JSON.stringify(info);
var infojson = JSON.parse(infojson);
db.open(function(err, db) {
if(!err) {
db.collection('testCollection', function(err, collection) {
collection.insert(infojson, {safe : true}, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
db.close();
}
});
});
}
return result;
});
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("You have added " + result + " to the database.");
response.end();
}
Here is the error I am getting:
/home/ubuntu/151_final/requestHandlers.js:36
response.write("You have added " + result + " to the database.");
^
ReferenceError: result is not defined
at Object.createData [as /createData] (/home/ubuntu/151_final/requestHandlers.js:36:40)
at route (/home/ubuntu/151_final/router.js:4:19)
at IncomingMessage.<anonymous> (/home/ubuntu/151_final/server.js:18:4)
at IncomingMessage.EventEmitter.emit (events.js:85:17)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socket.ondata (http.js:1690:22)
at TCP.onread (net.js:402:27)
I think you should do
db.open(function(err, db) {
if(!err) {
db.collection('testCollection', function(err, collection) {
collection.insert(infojson, {safe : true}, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
db.close();
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("You have added " + result + " to the database.");
response.end();
}
});
});
}
});
This is not a scope issue it's just that the call is async and result it's not defined because the line
response.write("You have added " + result + " to the database.");
is executed immediately, it doesn't wait for the other function to return