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.
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) methoddoUpsert
: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...