2012-10-12 70 views
1

我的大學課程剛剛開始通過mongodb,我們有一個任務要開展。到目前爲止,一切看起來都很順利,但我遇到了一個問題,在我的response.write中返回一個值。範圍問題似乎總是困擾着我。下面是代碼:無法返回值(我相信範圍問題)

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(); 
} 

這裏是我得到的錯誤:

/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) 

回答

1

我認爲你應該做

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(); 
            } 
          }); 
        }); 
      } 

    }); 

這不是一個範圍問題,它只是呼叫是異步的並且導致它沒有被定義,因爲行

response.write("You have added " + result + " to the database."); 

立即執行,它不會等待其他函數返回

+0

那麼,範圍也是如此。由於異步性質,值不會是正確的,但缺少變量是範圍問題;-) –

+0

太棒了!感謝Nicola的幫助。在此之前,我很習慣於在其他事情之外做出迴應,但我沒有想到要將它們嵌入其他事物中。 –

+0

嗯,我現在沒有得到任何錯誤,但現在我得到「您已經添加了[對象對象]到數據庫。」然而,這個對象在console.log消息中顯示得很好。 –