mongoose.js服务器 – 用于查询数据的res.write不会将数据发送回客户端

我正在尝试设置一个简单的mongoosetesting服务器来读取用户集合中的用户并打印用户名。 我似乎无法得到res.write的查询数据显示在客户端

var mongoose = require('mongoose'); var db = mongoose.createConnection('localhost', 'bugtraq'); var schema = mongoose.Schema({ username : 'string', email : 'string' }); var User = db.model('User', schema); var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); User.find().exec(function (err, users) { if(err) { res.write(err.message); } if(users) { users.forEach(function(u){ console.log(u.username); return '<b>'+u.username+'</b>'; }); } }); res.write('</body></html>'); res.end(); }).listen(8124, "127.0.0.1"); console.log('Server running at http://127.0.0.1:8124/'); 

服务器端输出是

 <html><head></head><body></body></html> 

我在控制台输出中看到了用户名

任何指针欢迎

你有两个问题。 首先,mongoose查询是asynchronous的,但是在查询实际发生之前(我必须重新确认代码)之前,你的回应是在callback之外结束的。

为了使它工作,你需要在User.find的callback函数中结束响应。

其次,你没有按照你的想法收集输出。 这一行是错误的:

 return '<b>'+u.username+'</b>'; 

你将发现的输出return在空气中。 如果您想在响应中返回,则需要捕获它。

把它放在一起,可能看起来像这样:

 User.find().exec(function (err, users) { if(err) { res.write(err.message); } if(users) { // here make a buffer to store the built output ... var output = []; users.forEach(function(u){ // (you saw this console output because this loop is happening, it's // just happening after your response has been ended) console.log(u.username); // ... then in each iteration of the loop, push to the buffer output.push('<b>'+u.username+'</b>'); }); } // finally, finish the response in the `find` callback. res.end(output.join() + '</body></html>'); });