Last active
August 29, 2015 14:03
-
-
Save saintc0d3r/13425514429cd56435fc to your computer and use it in GitHub Desktop.
[MongoDb][Node.js] Simple CRUD Demo against a Replica sets ( Raid-1, master-slaves cluster)
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
/** | |
* Simple code to demonstrate CRUD function on a document against an replica set. | |
* Run this command in this source code's directory to install required dependency: npm install mongodb | |
*/ | |
var MongoClient = require('mongodb').MongoClient; | |
var assert = require('assert'); | |
// Notice that the difference of connection string for connecting to a replica set and a single mongodb server, | |
var connection_string = "mongodb://127.0.0.1:27018, 127.0.0.1:27019, 127.0.0.1:27020/restaurant"; | |
MongoClient.connect(connection_string, function(err, db){ | |
if (err) throw err; | |
console.log("[INFO] - Connection to '"+connection_string+"' is established..."); | |
var menus = db.collection('menus'); | |
// Create a document & insert it into the database | |
var new_document = { | |
'name': 'Chicken Curry Rice', | |
'price': 2.5 | |
}; | |
menus.insert(new_document, function(err, inserted){ | |
if (err) throw err; | |
assert.ok(inserted != null); | |
console.log('[INFO] - Successfully inserted '+ JSON.stringify(inserted)+' document into the database.'); | |
// Retrieve the created document | |
menus.findOne({'name': inserted[0].name }, function(err, doc){ | |
if (err) throw err; | |
assert.notEqual(doc, null, 'findOne should return result'); | |
console.log('[INFO] - Retrieved document: '+JSON.stringify(doc)); | |
// Update the created document | |
var doc_id = doc._id; | |
menus.update({_id: doc_id}, {'$set': {'price': 5.0}}, function(err, updatedDoc){ | |
if (err) throw err; | |
console.log('[INFO] - Successfully updated '+updatedDoc+' document.'); | |
// Delete the created document | |
menus.remove({_id:doc_id}, function(err, removedDoc){ | |
if (err) throw err; | |
console.log('[INFO] - Successfully removed '+removedDoc+' document.'); | |
console.log("[INFO] - Closing database connection ..."); | |
return db.close(); | |
}); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment