Simple NodeJS run on server directly (not invoked through web) to execute some simple database operations on a MongoDB.
assumes you have previously created a mLab MongoDB account (look here on how to do through Heroku addon)
/* * Taken from http://docs.mongodb.org/ecosystem/drivers/node-js/ * A Node script connecting to a MongoDB database given a MongoDB Connection URI. */ var mongodb = require('mongodb'); // Create seed data -- it is in JSON format var seedData = [ { { // Standard URI format: mongodb://[dbuser:dbpassword@]host:port/dbname //using mongodb module mongodb.MongoClient.connect(uri, function(err, db) { if(err) throw err; /* var songs = db.collection('songs'); // Note that the insert method can take either an array or a dict. if(err) throw err; if(err) throw err; /* * Finally we run a query which returns all the hits that spend 10 or * more weeks at number 1. */ songs.find({ weeksAtOne : { $gte: 10 } }).sort({ decade: 1}).toArray(function (err, docs) { if(err) throw err; docs.forEach(function (doc) { console.log('In the ' + doc['decade'] + ', ' + doc['song'] + ' by ' + doc ['artist'] + ' topped the charts for ' + doc['weeksAtOne'] + ' straight weeks.'); }); // uncomment the following code if you wish to drop the collection (like a table) songs /***************************commented OUT songs.drop(function (err) { if(err) throw err; // Only close the connection when your app is terminating. }); */ }); } ); }); }); |
Now install mongodb module in the
myapp
directory and save it in the dependencies list. For example:$ npm install mongodb --save
Run the app with the following command:
$ node nodeJSMongoDBTest.js
question: What will happen if you rerun the code? try it out.
Understanding some of the code -see CRUD (create, read, update, delete) in action
mongodb.MongoClient.connect(uri, function(err, db) connect to specified uri and execute function upon connection var seedData = [ { decade: '1970s', artist: 'Debby Boone', song: 'You Light Up My Life', weeksAtOne: 10 }, { decade: '1980s', artist: 'Olivia Newton-John', song: 'Physical', weeksAtOne: 10 }, { decade: '1990s', artist: 'Mariah Carey', song: 'One Sweet Day', weeksAtOne: 16 } ];This is the JSON object representing 3 entries in our songs collection we want to enter.
NOTE: we have 4 idices (like columns) in our songs collection (like a databasetable) and they are:
- decade
- artist
- song
- weeksAtOne
songs.insert(seedData, function(err, result) try to insert new entries into the songs collection first creating the collection if it does not already exist
the entries are represented by the json object "seedData"
execute the function upon callback (being done)
songs.update(
{ song: 'One Sweet Day' },
{ $set: { artist: 'Mariah Carey ft. Boyz II Men' } },
function (err, result)update entry with song='One Sweet Day' to change the artist to ='Mariah Carey ft. Boyz II Men'
when done call the call back funciton specified
songs.find({ weeksAtOne : { $gte: 10 } }).sort({ decade: 1 }).toArray(function (err, docs) {
this is like a select (read) statment where weeksAtOne>10 and sorting by decade in asscending order (that is the :1) and then get results as an array that is passed to the call back function function (err, docs) {if(err) throw err;docs.forEach(function (doc) { console.log('In the ' + doc['decade'] + ', ' + doc['song'] + ' by ' +
doc['artist'] + ' topped the charts for ' + doc['weeksAtOne'] +
' straight weeks.'); });This cycles through the docs[] array representing the retrieved entries from the songs collection.
Note you access items by indexing the array docs[] with a column value called an index in mongoDB collection
while more work creating an API initially, it means that you DONT DUPLICATE the work from your different interfaces like a web (Angular), different server application (e.g. NodeJS) or a mobile App (e.g. iOS).
What does it mean to create an API --- you create a series of spearate applications (like in NodeJS with Express) that serve up results of desired CRUD operations on your Database that are accessed via WEB URLs ---example