mLAB Insert document into a collection API - javascript

Below is the code snippet I am using :
request.post('https://api.mlab.com/api/1/databases/db/collections/coll?apiKey=APIKEY',
{ json: {result} },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("----->"+body);
}
else
console.log("-----XXXXX>"+error);
});
Now result is a javascript var which is a string and has a proper json stored in it in the below form:
{
"key1":"value1",
"key2" : "value2",
....
"key100":"value3"
}
So basically in collection coll I need to insert above json as a document.
Output of above code is below :
{
"_id": {
"$oid": "5a71c84ac2ef165da041df86"
},
"result": "{\"key1\":\"val1\",\"key2\":\"val2\"}"
}
The above is the Json document that I am getting after executing the piece of NodeJs code shown at top and also I have shown the contents of string result.
I just need at the a json document like below:
{
"key1":"val1",
.....
"key100":"val100"
}

Related

How to update a certain field in object using the Nodejs Request Patch while keeping the others as before

I have a API which returns the JSON data something like this:
{
"data":{
"id": "859545",
"name":"Batman",
"custom-fields": {
"--f-09":"custom-1",
"--f-10":"custom-2",
"--f-11":"custom-3"
},
"tags": [],
"created-at": "2021-09-10T15:45:16Z",
"updated-at": "2022-04-23T11:52:49Z"
}
}
For this JSON I would like to change the field "--f-09" to "custom-1, custom-new" and "--f-10" to "custom-2, custom-new" while keeping all other fields as before.
I am aware that I can use request.PATCH in Nodejs for this but in that case, I need to provide all the data again for the request which I would like to avoid. I just want to update certain fields while keeping others as before.
In this example, I have provided a simple example which contains only certain fields but in my real code I have many fields so does this mean that I need to build the response body json using all the fields again and just change the --f-09 and --f-10?
Following is the code:
const jsonBody = {
"data": {
"id": "859545",
"name": "Batman",
"custom-fields": {
"--f-09": "custom-1, custom-new",
"--f-10": "custom-2, custom-new",
"--f-11": "custom-2"
},
"tags": [],
"created-at": "2021-09-10T15:45:16Z",
"updated-at": "2022-04-23T11:52:49Z"
}
}
request.patch('https://reqres.in/api/users',jsonBody,function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
console.log(response.statusCode);
}
}
);
Does this mean that I need to build the complete JSON body again here just like I have built the jsonBody above while using the PATCH or is there any other way where I can just pass the value for --f-09 and --f-10?
First you check, what parameters do you want update is side the object. then you can filter , that values only. then you can merge separate parts in the object.

DataTable with JSON data

I am trying to create a table using DataTable but having a hard time getting DataTable to load with JSON object.
function getData() {
var request = new XMLHttpRequest();
var json = "link-to-my-json-object";
// Get JSON file
request.onload = function() {
if ( request.readyState === 4 && request.status === 200 ) {
var JSONObject = JSON.parse(request.responseText);
createTable(JSONObject);
} else if(request.status == 400) { console.log("Error", request.status);}
};
request.open("GET", json, true);
request.send();
}
Requesting the JSON file via a XMLHttpRequest() request.
short sample of the JSON object:
{
"meta": {
"version": 1,
"type": "test"
},
"reports": [
{
"report-metadata": {
"timestamp": 1528235303.721987,
"from-ip": "0.0.0.0"
},
//and so on...
Currently only trying to show the meta part in a DataTable table:
function createTable(jsonData){
$(document).ready(function(){
$('#table').dataTable({
data: jsonData,
columns: [
{ data: 'meta.type' },
{ data: 'meta.version' }
]
});
});
}
index.html part:
<table id="table" class="display" style="width:100%"></table>
Only getting a No data available in table when running, and I am obviously missing something.
The "data" attribute for initializing your Data Table is expecting a list (Each element representing a row). Modify your ajax response, so each row is an element in the jsonData list. I also added quotes around all the JSON options.
var jsonData = [
{ "meta": { "version": 1, "type": "test" } }
];
$('#table').DataTable({
"data": jsonData,
"columns": [
{ "data": "meta.type" },
{ "data": "meta.version" }
]
});
https://datatables.net/reference/option/data
Since you want to load your data via ajax, you should look at the ajax options built in to the DataTables API. https://datatables.net/manual/ajax

Data not inserted in the collection

I am trying to insert document in a collection. The structure of the document looks like this:
[{
"observationNum" : 1231,
"observation_data": [{
"child_id": 1234,
"child_observation_data": [{
"activity_performed": true,
"observation_date": 15062016,
"teacher_id": 6789
}]
}]
}]
To achieve this, I have created 3 models. A Model named child_observation_data containing it's data as shown in the JSON structure above. Another Model named observation_data containing child_id and child_observation_data. I am trying to insert the data in the collection as shown below however the data isn't inserted in the observation_data model and child_observation_data model. What am I doing wrong?
function insertData() {
var childObservationDataModelObject = ChildObservationData.ChildObservationData({"activity_performed": true, "observation_date": "17May2016", "teacher_id":789});
var observationDataModelObject = ObservationData.ObservationData({"child_id" : 21386, "child_observation_data":childObservationDataModelObject});
var activityModelObject = new ActivityModel({"observationNumber" : 123456, "observation_data": observationDataModelObject});
activityModelObject.save(function(err, savedObject) {
if(err) {
console.error("error in saving:", err);
return;
}
if(savedObject != null)
console.log("Data saved ", savedObject);
});
ObservationData.getObservationDataModel()
.findOne({"child_id" : 21386})
.populate('child_observation_data')
.exec(function (err, activity) {
if (err)
console.log("error in finding", err);
console.log('The creator is ', activity);
});
}
The console logs are:
Data saved { observation_data: [ 57eb905265ddc958133ac649 ],
_id: 57eb905265ddc958133ac64a,
observationNumber: 123456,
__v: 0 }
The creator is null

Restangular getList() method not returning JSON

I have problem with geting a data from Restangular promise. I always get a promise instead of pure data in JSON.
This is response from my API
localhost:3000/api/meal
{
"status": "success",
"data": [
{
"meal_id": 4,
"meal_type_id": 2,
"description": "blahblah",
"price": "3.50",
"info": "120/120/20g",
"restaurant_id": 2
},
...
...
}
],
"message": "Retrieved ALL meals"
}
This is my config method for extracting data from response
RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
var extractedData;
// .. to look for getList operations
if (operation === 'getList') {
// .. and handle the data and meta data
return data.data;
} else {
extractedData = data.data;
}
return extractedData;
});
This is how I am trying to get data from my API
Restangular.all('meal').getList().then(function(meals) {
$scope.menu = meals; //meals.plain()
console.log($scope.menu);
});
but i always get this response
I need just JSON array from "data" field for using in my application.
Sry guys, after hours of research and debuging I found bug in my backend API in one specific select. Now Express.js, pg-promise and application works correctly.

ElasticSearch Javascript, Highlight not working

we switched recently to ElasticSearch Angular version and everything is working as expected except the Highlight, which is not returned at all.
This is how I setup a demo query:
$esClient.search({
index: 'myIndex',
body: {
size: 10,
from: 0,
query: query,
highlight: {
fields: {
"_all": { "pre_tags": ["<em>"], "post_tags": ["</em>"] }
}
}
}
}).then(function (result) {
// map the resultset for Row Template
var currentRows = result.hits.hits.map(function (record) {
return {
"type": record._type,
"entity": record._source, // the result
"highlight": record.highlight, // the highlights
"id": record._id // Search record ID
};
});
});
If I use the same code with a classic XmlHttpRequest and pass the query model inlcuding the highlight, I get back a JSON which contains an highlight array per each result, while using the ElasticSearch Angular client the query succeed but I don't get back the highlight.
Am I doing something wrong?
I think you might want to change to this format:
{
"query" : {...},
"highlight" : {
"pre_tags" : ["<tag1>"],
"post_tags" : ["</tag1>"],
"fields" : {
"_all" : {}
}
}}
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html

Categories

Resources