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

标签 node.js mongoose

我正在尝试设置一个简单的 Mongoose 测试服​​务器,该服务器读取用户集合中的用户并打印用户名。我似乎无法让 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 查询是任意同步的,但在查询实际发生之前,您将在回调之外结束响应(我必须重新缩进代码以确保)。

要使其正常工作,您需要在 User.find 的回调函数内结束响应。

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

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

您将查找的输出返回到稀薄的空气中。如果您想在响应中返回它,您需要捕获它。

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

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

关于node.js - mongoose.js 服务器 - 查询数据的 res.write 不会将数据发送回客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13434974/

相关文章:

javascript - 浏览器如何知道加载进度?

javascript - 如何使用套接字将按钮的背景颜色数据发送到服务器

node.js - 为什么 "babel-node"会旋转 2 个进程?

javascript - 如何使用 docker-container 运行网络应用程序?

javascript - 如何在集合中过滤mongoDB中的查询

node.js - 如何使用 Mongoose 从集合的所有文档中删除指定字段?

node.js - Mongoose 连接

node.js - 如何将 Restify 调用路由到另一个文件中编写的函数

node.js - 如何将 $split 运算符与聚合结合使用

node.js - 在 Mongoose Schema 中创建一个字段,该字段是对同一文档中其他字段的引用