LearnBoost/mongoose — Issue #748: Records not saving when primary mongod instance (of replica set) is asked to stepDown()
Author: leejsinclair
Created: 2012-02-25 03:16:20+00:00
State: open

The issue I found may reside somewhere between mongodb and mongoose. It occurs when the primary mongod service is stopped or is asked to step down.

# Here is a test that I crafted
The result of this test is that Lee is saved but not Darby

```JavaScript
var mongoose = require('mongoose');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;

var userModel = new Schema(
{
name: String,
username: String,
});

mongoose.model('user',userModel);
var connects = 'mongodb://127.0.0.1:17037/users, 127.0.0.1:17038/users';
mongoose.connectSet(connects, function(err) { console.log(err) });
mongoose.connection.on('open', function () {
console.log("mongodb connection open");
});

var user = mongoose.model('user');
u = { "name": "Lee", "username":"lee" };
saveRecord(user, u, 1);

// Send the primary mongod service a rs.setDown() command (before the below 30 second timeout)

setTimeout(function(){
u = { "name": "Darby", "username":"darbs" };
saveRecord(user, u);
}, 30000);

function saveRecord( model, obj ) {
var rec = new model(obj);
rec.save( function(err){
if(err!=null) {
console.log("Save failed");
}
});
}

```

# Here is my solution
The result of this test is that Lee and Darby are saved

```JavaScript
var mongoose = require('mongoose');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;

var userModel = new Schema(
{
name: String,
username: String,
});

mongoose.model('user',userModel);
var connects = 'mongodb://127.0.0.1:17037/users, 127.0.0.1:17038/users';
mongoose.connectSet(connects, function(err) { console.log(err) });
mongoose.connection.on('open', function () {
console.log("mongodb connection open");
});

var user = mongoose.model('user');
u = { "name": "Lee", "username":"lee" };
saveRecord(user, u, 1);

setTimeout(function(){
u = { "name": "Darby", "username":"darbs" };
saveRecord(user, u, 1);
}, 30000);

function saveRecord( model, obj , depth) {
if(depth>=5) {
console.log("unable to save record");
return;
}

var rec = new model(obj);

rec.save( function(err){
if(err!=null) {
mongoose.connectSet(connects, function(err) { console.log(err) });
setTimeout(function() {
saveRecord( model, obj, depth++);
},5000);
}
});
}

```

I think that two things are happening here:

* the mongod instances do not process save/update or find requests while a primary replica set is being voted upon; and
* mongoose is not switching it's connection to the primary mongod instance when it stepsDown().