Skip to content

Instantly share code, notes, and snippets.

@andrewjstone
Created October 13, 2011 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewjstone/1283054 to your computer and use it in GitHub Desktop.
Save andrewjstone/1283054 to your computer and use it in GitHub Desktop.
node-mongodb-native improper behavior with w:2 for insert and findAndModify
// Run this with 'nodeunit safeErrors.js'
//
// Create a replica set with only 1 replica up and do an insert with w:2 and findAndModify
// with w:2. Note that the insert returns right away successfully, even though the data
// was not replicated. The findAndModify has different behavior. It actually times out
// but still returns success!
var mongo = require('mongodb'),
Db = mongo.Db,
Server = mongo.Server,
ReplSetServers = mongo.ReplSetServers
;
var inspect = require('util').inspect;
exports['hang on findAndModify'] = function(test) {
var replSet = new ReplSetServers([
new Server('s1', 27017)
], {rs_name: 'rs'});
var db = new Db('test', replSet);
db.open(function(err, client) {
if (err) console.log(err);
test.ok(!err);
client.dropDatabase(function(err) {
test.ok(!err);
var collection = new mongo.Collection(client, 'contests');
var beforeInsert = new Date().getTime();
collection.insert({play_cursor: 101, plays: [{
timestamp: new Date(),
active: false,
uuid: "44acfea5-d321-4e43-bb85-61be896a9ccb"
}]}, {safe: {w:2, wtimeout: 5000}}, function(err, docs) {
var afterInsert = new Date().getTime();
var diff = afterInsert-beforeInsert;
console.log("insert time = "+diff);
var contest = docs[0];
var play = contest.plays[0];
var beforeFindAndModify = new Date().getTime();
collection.findAndModify(
{_id: contest._id, 'plays.uuid': play.uuid},
[],
{$set : {'plays.$.active': true, 'plays.$.cursor': contest.play_cursor}},
{new: true, fields: {plays: 0, results: 0}, safe: {w:2, wtimeout: 5000}},
function(err, contest) {
var afterFindAndModify = new Date().getTime();
var diff = afterFindAndModify - beforeFindAndModify;
console.log("findAndModify time = "+diff);
db.close();
test.done();
}
);
});
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment