Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using REST to search MongoDB


By now, that you might be wondering where JSON comes into play when using MongoDB. When you access a MongoDB database instance using a RESTful interface such as mongo-rest, the documents are transferred to the client using JSON. Let's see how to get a list of documents from MongoDB.

How to do it...

Using REST with Node.js and MongoDB takes several steps.

  1. Be sure you've set up the REST server as we discussed in the introduction. You'll need to have created the files rest-server.js, routes/documents.js, and mongo-rest-example.html with the UI for our RESTful application, and run both the REST server and the document server with Node.js.

  2. Second, be sure that you're running MongoDB.

  3. Next, to process the REST GET request, we need to define the function exports.findAll in documents.js, which should look like this:

    exports.findAll = function(req, res) {
      db.collection('documents', function(err, collection) {
        collection.find().toArray(function(err, items) {
          res...