Last active
December 17, 2015 03:29
-
-
Save niallo/5543475 to your computer and use it in GitHub Desktop.
Simple Mongoose program to facilitate testing MongoDB auto-reconnect in client
This file contains 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
// | |
// Program to query a local mongodb every second. This should auto-reconnect. | |
// | |
// Instructions: | |
// | |
// 1) start mongod | |
// 2) npm i [email protected] && node reconnect-mongoose.js | |
// 3) kill mongod | |
// 4) after a short interval, restart mongod | |
// | |
// Mongoose (3.6.9) should auto-reconnect when mongod has restarted, | |
// but doesn't appear to. | |
// | |
/* | |
Sample output: | |
$ node reconnect-mongoose.js | |
mongodb query ok | |
mongodb query ok | |
mongodb query ok | |
mongodb query ok | |
(KILL mongodb in another term) | |
mongo connection error: [Error: failed to connect to [localhost:27017]] | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
(START mongodb in another term) | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
mongodb query not ok | |
*/ | |
var mongoose = require('mongoose') | |
mongoose.model('user', new mongoose.Schema({ username: String, email: String })) | |
var mongoUrl = "mongodb://localhost/mydb" | |
mongoose.connect(mongoUrl, function(err) { | |
if (err) throw err | |
var users = mongoose.model('user') | |
mongoose.connection.on('error', function(e) { | |
console.log("mongo connection error: ", e) | |
}) | |
// Run a simple 'find' query every second | |
setInterval(function() { | |
users.findOne(function(err, collection) { | |
if (err) { | |
return console.log("mongodb query not ok") | |
} | |
console.log("mongodb query ok") | |
}) | |
}, 1000) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment