mongodb insert and return id with REST API - mongodb

New to Mongodb,trying to get _id after mongodb insert without a round trip.
$.ajax( { url: "https://api.mongolab.com/api/1/databases/xxx/collections/xx?apiKey=xxx",
data: JSON.stringify( [ { "x" : 2,"c1" : 34,"c2" : getUrlVars()["c2"]} ] ),
type: "POST",
contentType: "application/json" } );
Thanks
edit: Solved buy removing square bracers JSON.stringify( { "x" : 2,"c1" : 34,"c2" : getUrlVars()["c2"]} )

You can't get the _id of the object without waiting for a response because the _id is generated on the server. You need to attach a success call to your request. The id is actually returned as a $oid member within an _id object.
This is assuming you are using $.ajax to make the request and the MongoLab REST API as documented at http://support.mongolab.com/entries/20433053-rest-api-for-mongodb
For example:
$.ajax( { url: 'https://api.mongolab.com/api/1/databases/xxx/collections/xx?apiKey=xxx',
data: JSON.stringify( {"x" : 1 } ),
type: "POST",
contentType: "application/json"}
).success(function(returnedData) {
alert(returnedData._id["$oid"]);
});

What REST API are you using? MongoDB does not ship with a REST API that does what you are trying to do.

According to the MongoLab REST API docs, the square braces are for inserting multiple docs at a time. For a single document, you simply need to JSON.Stringify a single valid JSON (BSON) document.

Related

URL parameter vs post form data

URL parameter or post form data; which is more computationally efficient for a backend API to query?
example:
GET : user/:id
POST: user/ { "id": "some_id" }

Sharepoint REST API filter empty LookUp field

I'd like to know how I can filter ListItems in SharePoint rest API (2013) on empty lookup.
On my list items, there is a lookup (single value, not required) and i'd like to get all items where lookup is empty (blank).
_api/web/lists/getbytitle('MyList')/items?$select=Id&$expand=MyLookUp/Id&$filter=??
Does someone has a clue ?
Thx
REST API in SharePoint 2013 does Not support null values for filtering on list item queries.
However you can combine CAML query with REST API to get the required data.
Please refer below code :
(Note : please change your query/URL):
function _rest_Post(rquest) {
return $.ajax({
method: rquest.method,
url: rquest.url,
contentType: rquest.contentType,
headers: rquest.header,
data: JSON.stringify(rquest.body),
});
}
function GetByCaml(serviceParams) {
var req = {
method: 'POST',
url: url + "/_api/web/lists/getByTitle('" + serviceParams.create.lName + "')/getitems",
header: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
body: serviceParams.create.body,
contentType: "application/json;odata=verbose",
};
return _rest_Post(req);
}
function getData(){
var queryViewXml = "<View><Query><Where><IsNull><FieldRef Name='Project_x0020_Manager'/></IsNull></Where></Query><ViewFields><FieldRef Name='Title'/></ViewFields></View>";
var params = {};
params.create= {};
params.create.lName = "MyList";
params.create.filter = "";
params.create.body = {
'query':{
'__metadata': { 'type': 'SP.CamlQuery' },
'ViewXml': queryViewXml
}
}
return GetByCaml(params);
};
getData().then(function(data){
//success handler
}, function(error){
//failure handler
});
OP, your answer is really close. The Id value for empty lookups should be -1. If you explore the raw data with something like SP CAML Query Helper you should see -1;# in the unselected lookups.
/items/?$select=Id,Title,Assigned_x0020_To/Id&$expand=Assigned_x0020_To&$filter=(Assigned_x0020_To eq -1) should work for you.
I just found a solution that does work using REST, you simply filter the lookup ID to greater than 0. All lookup IDs are 1 or greater, but using not equal to 0 (MyLookup ne 0) fails, because null is not equal to 0. However, null is, apparently, not GREATER THAN 0, either. It might make the math geeks twitch, but it works.
_api/web/lists/getbytitle('abc')/items?$select=Id&$expand=MyLookUp/Id&$filter=MyLookup gt 0

Sharepoint 2013 REST API not returning all items for a list

The title states my problem quite exactly. If I try to gather all 400+ items from a list using sharepoint's REST API, I only get first 100.
I have read http://msdn.microsoft.com/en-us/library/office/dn292552(v=office.15).aspx and in the "Working with list items by using REST" part, they're stating that
The following example shows how to retrieve all of a list’s items.
url: http://site url/_api/web/lists/GetByTitle(‘Test')/items
method: GET
headers: ...
I have highlighted word all, because that's not what I'm getting ...
Am I missing something? Is there some option I should disable/enable to gett truly all items?
Thanks
The limitation is due to server side paging.
A workaround is to retrieve 100 items at a time, or override the limitation by entering a count of items:
https://$DOMAIN/$SITE/_api/web/Lists/getByTitle('$LIST')/Items?$top=1000
Note that there is also a threshold at 5000.
You can use RowLimit & RowsPerPage in rest call. Below is the example
$.ajax({
url: siteurl + "/_api/web/lists/getbytitle('NewList')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
RowLimit : null, //Specify the row limit
RowsPerPage : null, //Specify no of rows in a page
success: function (data) {
$('#oDataFilter').append("<table>");
$.each(data.d.results, function(index, item){
$('#oDataFilter').append("<tr><td class="+styleClass+">" + item.ID + "</td><td class="+styleClass+">"+ item.Title + "</td></tr>");
});
$('#oDataFilter').append("</table>");
},
error: function (error) {
alert('Error getListItems :: '+JSON.stringify(error));
}
Adding to Christophe's answer I would say listing all (potentially 5000) items in a list and parsing them would result in performance issues.
If you query sharepoint to show all items in a particular list it would only print out the first 100. But the xml response also provides the url to query for the next 100 list items.
At the very end of the xml response you will see a tag like this
<link rel="next" href="https://xxxxx.sharepoint.com/_api/web/lists/GetByTitle('list')/items?%24skiptoken=Paged%3dTRUE%26p_ID%3d100" />
The url inside href="...."is what you'll need.
Querying the above would provide you with a list of the next 100 or less items.
If there are still more items left this xml response would in turn provide an other <link rel="next"> tag and if not this tag won't exist.
Better to handle 5000 items in sets of 100 rather than them all together in my opinion.
To anyone now seeing this, you can use data.d.__next to get the next 100 items. Using some good old recursion, you can get all the items like so
function getItems(url) {
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(data) {
console.log(data);
// Do work
if (data.d.__next) {
getItems(data.d.__next);
}
},
error: function(jqxhr) {
alert(jqxhr.responseText);
}
});
}

Non-standard REST API in Backbone js

I am building Backbone.js models backed by a legacy REST API. When I create a new resource on the server, rather than return the JSON of the newly created resource, it returns plain text of the id of the newly created resource, along with a relative URL in the Location header where the resource can be gotten.
For example, I POST:
{ "firstName": "Joe", "lastName": "Blow" }
to http://fakeserver.com/people and (on success) the body of the plain/text response might be: "1234". The status of the response is 201 and the Location header would be http://fakeserver.com/people/1234. If I GET from that Location URL, it will have
{ "id": 1234, "firstName": "Joe", "lastName": "Blow" }
How would I override the sync function on my model to accommodate this convention instead of the default Backbone.js conventions?
To clarify, there is no Backbone.js version of this yet - I am trying to create a new one. The old jQuery-only way of doing it was:
$.ajax({
type: 'POST',
url: submitURL,
data: $.toJSON(person),
success: function(data, status, request) {
showSuccessMessage();
closeDialog();
},
dataType: 'json',
contentType: 'application/json'
});
The details of the showSuccessMessage and closeDialog are unimportant - just to demonstrate that basically we are just ignoring the content of the response and throwing the original object away.
Handle the simple text response with parse:
http://backbonejs.org/#Model-parse
parse : function(response, options){
console.log(response, options);
var data = this.toJSON(): //current model to hash
data.id = response; <- assuming that response is a simple text plain id
return data;
}
You could also use sync to overwrite something in the ajax call(that is not supported in the options hash.
http://backbonejs.org/#Model-sync

MongoLab API Update: message: "Update object is missing."

Unable to update data in the data base. The above is a request link.
https://api.mongolab.com/api/1/databases/my-db/collections/my-coll/52f7b875e4b0e615e67f0a41?jsonbody=[{"_id":"52f7b875e4b0e615e67f0a41","like":"true"}]&apiKey=my_api_key
Got. 400 Bad Request error and message: "Update object is missing."
Or anyone can give an example to update mongodb via REST API in java would be very helpful.
Thanks.
It looks like you're missing the actual update spec, which should be the body of the PUT request. The MongoLab Data API docs include example of how to do that from jQuery, the key bits of which I've copied below for your convenience.
$.ajax( { url: 'https://api.mongolab.com/api/1/databases/my-db/collections/my-coll?apiKey=myAPIKey&q={"_id":1234}',
data: JSON.stringify( { "$set" : { "x" : 3 } } ),
type: "PUT",
contentType: "application/json" } );
Note that the $set update operator is not part of the url, but the body (which you specify in jQuery using the data field).