Last active
December 19, 2018 19:08
-
-
Save joewright/2fb34b2576805b94fcc1 to your computer and use it in GitHub Desktop.
Stream mongo query through an express server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
this is very nice
updated to use native JS promises
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ran this recently for fun and was disappointed to see the
stream
interface removed from mongoose. updated it to work again