Skip to content

Instantly share code, notes, and snippets.

@MCheli
Created June 19, 2016 21:09
Show Gist options
  • Save MCheli/9bf5027f175371d861cd5208f53a481b to your computer and use it in GitHub Desktop.
Save MCheli/9bf5027f175371d861cd5208f53a481b to your computer and use it in GitHub Desktop.
Simple Node and MongoDB Interaction
var assert = require('assert');
exports.insertDocument = function(db, document, collection, callback) {
// Get the documents collection
var coll = db.collection(collection);
// Insert some documents
coll.insert(document, function(err, result) {
assert.equal(err, null);
console.log("Inserted " + result.result.n + " documents into the document collection "
+ collection);
callback(result);
});
};
exports.findDocuments = function(db, collection, callback) {
// Get the documents collection
var coll = db.collection(collection);
// Find some documents
coll.find({}).toArray(function(err, docs) {
assert.equal(err, null);
callback(docs);
});
};
exports.removeDocument = function(db, document, collection, callback) {
// Get the documents collection
var coll = db.collection(collection);
// Delete the document
coll.deleteOne(document, function(err, result) {
assert.equal(err, null);
console.log("Removed the document " + document);
callback(result);
});
};
exports.updateDocument = function(db, document, update, collection, callback) {
// Get the documents collection
var coll = db.collection(collection);
// Update document
coll.updateOne(document
, { $set: update }, null, function(err, result) {
assert.equal(err, null);
console.log("Updated the document with " + update);
callback(result);
});
};
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var dboper = require('./operations');
// Connection URL
var url = 'mongodb://localhost:27017/conFusion';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
dboper.insertDocument(db, { name: "Vadonut", description: "Test" },
"dishes", function (result) {
console.log(result.ops);
dboper.findDocuments(db, "dishes", function (docs) {
console.log(docs);
dboper.updateDocument(db, { name: "Vadonut" },
{ description: "Updated Test" },
"dishes", function (result) {
console.log(result.result);
dboper.findDocuments(db, "dishes", function (docs) {
console.log(docs)
db.dropCollection("dishes", function (result) {
console.log(result);
db.close();
});
});
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment