我的大学课程刚刚开始涉及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)
答案 0 :(得分: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.");
立即执行,它不会等待其他函数返回