【问题标题】:Non-blocking write to response from Mongo in JSON format以 JSON 格式非阻塞写入来自 Mongo 的响应
【发布时间】:2016-03-23 16:02:36
【问题描述】:

我正在使用 Node/Express.js,因此 GET 路由将从 Mongo 数据库中检索所有文档(足够简单)。正如代码所示,我能够以非阻塞方式完成此操作。但是,当我取消注释将响应设置为 JSON 格式的行时,我收到语法错误 - 因为虽然每个文档都是 JSON 格式,但文档的聚合不是 JSON 格式。如何保持非阻塞数据流,但将它们发送为application/json

我在 GET 路由下方包含了我用来从 mongo 数据库中获取项目的函数。

获取路线:

app.get('/people', function(req, res){
    //res.set('Content-Type', 'application/json');
    mongoDriver.get(null, function(err, code, document){
        res.status(code);
        if(err) {
            res.write(JSON.stringify(err));
        } else if(document){
            res.write(JSON.stringify(document));
        }
        if(!document){
            res.end();
        }
    });
});

我的 mongo 实现的相关部分。

var cursor = db.collection(self.collection).find(data);
        cursor.each(function(err, doc) {
            if(err) {
                return callback(err, 500);
            } else if (doc !== null) {
                return callback(null, 200, doc);
            } else {
                db.close();
                return callback(null, 200, null);
            }
    });

【问题讨论】:

    标签: javascript json node.js mongodb express


    【解决方案1】:

    使用来自mongodb NPM 包的tutorialres.json(...)

    // ...
    
    findDocuments(db, function(docs) {
        db.close();
        res.json(docs);
    });
    
    // ...
    

    【讨论】:

    • 因此本教程使用 .toArray() 方法,而我的代码使用光标悬停在集合上。我在这里可能是错的,但不是 .toArray() 方法阻塞。它将等到每个文档返回并将其放入数组中。
    • 基本上每个 mongo 方法都是异步的——所以它根本不会阻塞。
    • 真的是异步@SterlingArcher吗? .toArray() 回调中的 'docs' 参数包含所有返回的文档(因为针对它调用了 .length)。这不像我的游标实现那样是非阻塞的。
    • 关键字有callback
    猜你喜欢
    • 2010-09-11
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多