I was finalist in the LinkedIn Hackday hackathon last November with my "Mobile Chow Finder" app using jQuery Mobile, Database.com and Ruby on Rails on Heroku. I really liked the Chow Finder use case but wanted to make it more of a finished application; not just something I threw together in a matter of hours. So I decided to start off by writing an API with Node.js and MongoDB and host it on Cloud Foundry. I'm going to build a website running off that API with something like Sinatra or Rails. I also want to eventually build HTML5, Android and iOS applications running off this API too.
The API has the following methods around two objects: locations and facilities.
GET /locations -- returns a list of locations
GET /locations/:id -- returns a location
POST /locations -- creates a location
GET /locations/favorites -- returns list of favorite locations for a user
POST /locations/favorites -- creates a new favorite for a user
GET /locations/:id/facilities -- returns a list of facilities for a location
POST /locations/:id/facilities -- creates a new facility for a location
GET /locations/:id/facilities/:id -- returns a facility
PUT /locations/:id/facilities/:id -- updates a facility
You can check out code for app.js on github, but most of the interesting stuff is around the connection to MongoDB and the code for the actual methods.
Once you installed the MongoDB native Node.js driver, you just need to create your connection to either your localhost or Mongo running on Cloud Foundry in app.js.
Now the API itself. What's great about Node and Mongo are that they both talk JSON. So in this method, we POST some JSON and simply insert it into the 'locations' collection.
To return all of the locations in the collection, we issue the find() command which returns a cursor object to the callback which is passed to the responses as an array of documents.
To return a specific location (as a document) from Mongo, we use the findOne() command and pass in the location's id from the URL.
To create a facility for a location, we POST the entire JSON for the facility and then add the id for the parent location from the URL before inserting it into the collection.
The last method updates a facility document with the findAndModify() method. The method finds the facility by id and updates the data PUT in the JSON payload.