frankgreco
frankgreco

Reputation: 1506

Non-blocking write to response from Mongo in JSON format

I am using Node/Express.js so that the GET route will retrieve all documents from a Mongo database (simple enough). I am able, as the code will show, to accomplish this in a non-blocking way. However, when I uncomment the line that sets the response to JSON format, I get a syntax error - because while each document is in JSON format, the aggregation of the documents aren't in JSON format. How can I keep the non-blocking data flow, but send them as application/json

I include below the GET route and also the function I am using to get the items form the mongo database.

GET route:

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

relevant portion of my mongo implementation.

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

Upvotes: 0

Views: 85

Answers (1)

Roman Dibikhin
Roman Dibikhin

Reputation: 856

Use a tutorial from a mongodb NPM package and res.json(...):

// ...

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

// ...

Upvotes: 1

Related Questions