Skip to content

Instantly share code, notes, and snippets.

@joewright
Last active December 19, 2018 19:08
Show Gist options
  • Save joewright/2fb34b2576805b94fcc1 to your computer and use it in GitHub Desktop.
Save joewright/2fb34b2576805b94fcc1 to your computer and use it in GitHub Desktop.
Stream mongo query through an express server
var express = require('express');
var mongoose = require('mongoose');
// connect to local db
mongoose.connect('mongodb://127.0.0.1:27017/swag', function(error) {
if (error) {
throw new Error(error);
}
});
// Mongoose Schema definition
var UserSchema = new mongoose.Schema({
name: String,
email: String
});
// user model
var User = mongoose.model('User', UserSchema);
// Bootstrap express
var app = express();
app.get('/', function(req, res) {
var rando = Math.floor(Math.random() * 10000);
new User({
name: 'dang' + rando,
email: 'someone' + rando + '@derp.net'
}).save();
// res.type('application/json');
res.write('<!DOCTYPE html><html><head><title>streamer</title>' +
'<style>pre {white-space: pre-wrap;}</style></head>' +
'<body><h1>Streaming JSON output from Mongoose</h1><pre><code>');
res.write('[');
var cursor = User.find().cursor();
cursor.eachAsync(writeDoc, allDone);
function writeDoc(doc) {
return new Promise(function(resolve) {
setTimeout(function() {
res.write(JSON.stringify(doc) + ',');
resolve();
}, 200);
});
}
function allDone() {
// hack to close JSON string...
res.write('{"thanks":true}]</code></pre></body></html>');
// res.end();
res.end();
}
});
app.listen(3000);
@joewright
Copy link
Author

ran this recently for fun and was disappointed to see the stream interface removed from mongoose. updated it to work again

@jonathanfann
Copy link

this is very nice

@joewright
Copy link
Author

updated to use native JS promises

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment