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 create a document in MongoDB


In principle, using REST to create a document is simple: create the JavaScript object on the client, encode it as JSON, and POST it to the server. Let's see how this works in practice.

How to do it...

There are two pieces to this: the client piece and the server piece.

  1. On the client side, we need some way to get the data for our new MongoDB document. In our example, it's the fields of the form on the HTML page, which we wrap up and POST to the server using the client-side (in the HTML) method doUpsert:

    function doUpsert(which)
    {
    Var id = $('#id').val();
    var value = {};
      value.call = $('#call').val();
      value.lat = $('#lat').val();
      value.lng = $('#lng').val();
    
      $('#debug').html(JSON.stringify(value));
    
    var reqType = which == 'insert' ? "POST" : 'PUT';
      var reqUrl = 'http://localhost:3000/documents/' + 
    (which == 'insert' ? '' : id);
    
      $.ajax({
        type: reqType,
        url: reqUrl,
        dataType: 'json',
        headers: { 'Content-Type' : 'application...