Skip to content

Instantly share code, notes, and snippets.

@saintc0d3r
Created July 13, 2014 04:07
Show Gist options
  • Save saintc0d3r/4f6b8c24c52cbfa0b1e2 to your computer and use it in GitHub Desktop.
Save saintc0d3r/4f6b8c24c52cbfa0b1e2 to your computer and use it in GitHub Desktop.
[MongoDb][Node.js] A simple demo of write concern settings when inserting documents on a replica set
/**
* Simple code to demonstrate write concerns setting when inserting documents into replica set.
* Run this command to install required dependency, in this source code's directory: npm install mongodb
*/
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
// Notice the url query string in the below connection string to replica set. We define write concern = 1 as the default write concern setting.
// w=1 means, the driver would returns success once a document has been successfully inserted into the Primary Node.
var connection_string = "mongodb://KURONO:27018, KURONO:27019, KURONO:27020/demo_replica_set?w=1";
MongoClient.connect(connection_string, function(err, db){
if (err) throw err;
console.log("[INFO] - Connection to '"+connection_string+"' is established...");
var test_docs = db.collection('test_docs');
// Create a document & insert it into the database
var test_doc = {
'value': Math.random()
};
test_docs.insert(test_doc, function(err, inserted){
if (err) throw err;
// Retrieve the created document
assert.ok(inserted != null);
console.log("[INFO] - Successfully inserted "+ JSON.stringify(inserted)+" document into the database using write concerns setting 'w=1'.");
var second_test_doc = {'value': Math.random()};
// w=2 means, the driver would returns success once a document has been successfully inserted into the Primary Node & also being synched to the Secondary node.
var write_concern = {'w':2};
// Insert another document with different write concerns setting (e.g. w=2).
test_docs.insert(second_test_doc, function(err, inserted){
if (err) throw err;
// Retrieve the created document
assert.ok(inserted != null);
console.log("[INFO] - Successfully inserted "+ JSON.stringify(inserted)+" document into the database using write concerns setting: "+JSON.stringify(write_concern));
console.log("[INFO] - Closing database connection ...");
return db.close();
});
});
});
@osher
Copy link

osher commented Aug 26, 2019

this is misleading.
defining a local var write_concern has nothing to do with your insert.

@abdelfattehsakkat
Copy link

You just defined a local variable.

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