I have 3 MongoDB collections and each of them are defined something like:
#app.route('/getMyData', methods=['GET'])
def getMyData():
myDataCollection = db["data_1"]
data = list(myDataCollection.find({},{"Name":1,"Website":1,"Twitter":1,"Description":1,"_id":0}))
return jsonify(data=data)
Then I retrieve these data using AJAX requests (one for each collection so 3 requests) as follows:
function getDataFromDB() {
$.ajax({
url: '/getMyData',
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
// code goes here
}
});
}
How can I simplify this? It seems like I cannot query multiple collections in MongoDB.
MongoDB is designed so that each operation/query deals with one collection.
MongoDB CRUD Introduction
The design of your DB should take this into consideration. So if you need lists of each collection you'll have to have one for each.
As Blakes Seven mentioned, what you could do is set up some server side script that makes the three calls, then organises the response 'data' so that you only have one call in your application. You're still having to make three DB calls though; just depends on your application/DB/server design.
Related
I have the exact same code running on two different servers, with the route returning a collection to an AJAX call. On my local machine, the response comes through as an array but on the remote and a coworker's machine it comes through as an Object.
Definitely the same code (pushed from local, pulled to remote)
The collections are definitely in the same format (did a dd() and they're the same)
The request and response headers are the same
It works on the remote if I DON'T sort the collection first, but that makes no difference to my local, and the dd()s look exactly the same.
Local response example (15 entries):
[{id: 80, title: "Banner, Bruce", eventColor: "green", order: 1, availability: false},.....]
Remote response example (29 entries)
{"0":{"id":18,"title":"Bond, James","eventColor":"green","order":1,"availability":false},.....}
AJAX:
$.ajax({
url: '/roster/' + roster_type + '/resources',
processData: false,
contentType: false,
async: true,
cache: true,
type: 'POST',
data: formData,
dataType: 'JSON'
}).done(function (resources) {
// This line right here works fine on my machine because the array has a length,
// not on the remote where resources.length is undefined
if(resources.length > 10 && view.type == 'resourceTimeGrid') {
changeView('resourceTimelineDay');
}
successCallback(resources);
getRosterEvents();
}).fail(response => {
showErrorMessage(response);
failureCallback(response);
});
The sortBy method sorts the collection by the given key. The sorted
collection keeps the original array keys, so in this example we'll
use the values method to reset the keys to consecutively numbered
indexes:
(Source: https://laravel.com/docs/6.x/collections#method-sortby - emphasis mine)
Using values() resets the array indexes, so JavaScript then sees a nice numbered array.
I'm using web api without deep understanding what it is, just knowing that each editable entity become a resource, that means has the uri, when web api provides the interpretation of PUT, POST, GET, DELETE HTTP commands to support CRUD operations. But what if for tracing/logging purpose I need to send correlation token together with e.g. GET request? Are there any recommendations and techniques to add to the HTTP request/routing "technical parameters"?
I have found something that need to be tested https://webapicorrelator.codeplex.com/ But actually I would prefer just to understand how it could work...
Or just add it to the heder using jquery ajax headers:
return $.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
url: url,
data: { ElectrodeId: electrodeId },
headers: { "X-CorrelationToken": correlationToken },
method: "POST",
dataType: "json",
success: function (data) {
}
I have a C# web application which uses ajax method to GET and POST data. Is there any difference between GET and POST methods in passing data (in case of contentType,data,dataType)?
$.ajax({
type: 'GET',
url: "url",
contentType: "application/json; charset=utf-8",
data: { value: "data" },
dataType:"json",
success: function (data) {
alert(data);
},
error: function (data) {
alert("In error");
}
});
});
GET encodes the information into the url, the more info you GET the longer your URL becomes.
POST stores data in an array and passes that array to the next page. your Url remains unmodified.
While that may not seem like a huge deal, URLs do have a maximum length and errors will ensue if you exceed it. In addition and call to a specific url may fail due to the modifications GET makes. Apart from that, They are similar enough in function to be interchangeable for most purposes.
In normal form method also GET is used to sent some insensitive small chunk of data to server in querystring, whereas POST is used for sending large and secure data to the server
In case of using ajax GET is commonly used, POST is feasible only when you have to do DB interactions on server or there's some sensitive data involved, read more here http://www.jquery4u.com/ajax/key-differences-post/
I have to query (via Ajax) 2 scripts at the same time.
I know for sure that one is really quick, it just displays some html, the second is doing some query using a WebService.
The quick request, is always sent after the first one. But with all my attempts, the fast/quick one, never completes before the slow one.
The code use to call the first long ajax request:
$.ajax({
type: "POST",
url: '/fr/ajax_flight_get_other_oneway',
cache: false,
dataType: 'json',
success: function(data) {
// some treatment
}
The code for the second faster ajax request:
$.ajax({
type: "POST",
url: '/fr/load_back_forflight?id=SN4422_23',
cache: false,
data: "comps="+compSelectedCodes+"&escale="+escale,
dataType: 'json',
success: function(data) {
// some treatment
}
Is it something in Apache that should be changed or is it in jQuery?
I found the solution to my problem, it was linked to the session.
the session was based on file system. So the first (long query) is lock the session file, and then the second one is forced to wait for the long query to finish.
by using session in DB, I've resolved the problem.
thanks for your help
Put the slow one in the success callback of the fast one. This will guarantee that the fast request will finish first before starting the second request.
It's possible that the browser decided to use the same HTTP connection for both (using the HTTP header Keep-alive) and thus it appears queued. This is not a jQuery thing -- it's something that browsers can opt to do.
Use your browser's HTTP network traffic debugger to see if that's the case.
If not, then your web-server may be only allowing one connection per client and is queueing them. See this:
How do I configure Apache2 to allow multiple simultaneous connections from same IP address?
Try this:
$.ajax({
type: "POST",
url: '/fr/ajax_flight_get_other_oneway',
cache: false,
dataType: 'json',
success: function(data) {
// some treatment
//The code for the second faster ajax request:
$.ajax({
type: "POST",
url: '/fr/load_back_forflight?id=SN4422_23',
cache: false,
data: "comps=" + compSelectedCodes + "&escale=" + escale,
dataType: 'json',
success: function(data) {
// some treatment
}
});
}
});
I'm using $.ajax asynchronously to send some json to a controller marked with [HttpPost], like this:
$.ajax({
url: location.href,
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: theJson,
async: true,
});
This works fine, but the method expects an ActionResult, I guess with a new view. But I don't want that - I just want to do a little update on the server without updating the page.
Is there any way to set up a method on the server to do the update, independent of the view?
You should change the method to return void.