I am trying to generate an Array with an object structure inside it with the following structure:
var valores = [{ name: 'MongoDB', type: 'float', value: 25,{ name: 'MongoDB', type: 'float', value: 5 },{ name: 'MongoDB', type: 'float', value: 2 }];
I get the following structure in my Rest API:
{
"subscriptionId" : "5a268a598dc68904bbc7b3cf",
"originator" : "localhost",
"contextResponses" : [
{
"contextElement" : {
"type" : "Temperatura",
"isPattern" : "false",
"id" : "S_Temp001",
"attributes" : [
{
"name" : "Tem_int",
"type" : "float",
"value" : 2,
"metadatas" : [
{
"name" : "accuracy",
"type" : "Float",
"value": 2 }
]
},
{
"name" : "Tem_out",
"type" : "Integer",
"value" : 1,
"metadatas" : [
{
"name" : "Timestap",
"type" : "Integer",
"value": 33 }
]
}
]
},
"statusCode" : {
"code" : "200",
"reasonPhrase" : "OK"
}
}
]
}
I have to process this data in my Back-end to generate the structure already mentioned above.
The way I am trying to generate my Array is as follows:
var params = req.body;
var tmp2 = [];
for (var i = 0; i < params.contextResponses.length; i++) {
for (var j = 0; j < params.contextResponses[i].contextElement.attributes.length; j++) {
for (var k = 0; k < params.contextResponses[i].contextElement.attributes[j].metadatas.length; k++) {
//console.log("nuevo log antes de petar: " + params["contextResponses"][i].contextElement.attributes[j].metadatas[k].value);
tmp2.push('{' + //paramsheadersFiware_Service,
params.contextResponses[i].contextElement.attributes[j].name,
params.contextResponses[i].contextElement.attributes[j].type,
params.contextResponses[i].contextElement.attributes[j].value
+ '}');
}
}
}
console.log("tmp2 --> ",tmp2);
Looping through the structure and then pushing to the new array.
The answer I get is the following:
[ '{Tem_int', 'float', '2}', '{Tem_out', 'Integer', '1}' ]
As you can see the format is not correct, I need the labels before the values I have tried concatenating before the Push but it does not work well and the '' are wrongly placed they should go inside {''} How can I solve this problem ?
The objective is to save multiple documents in MongoDB according to the initial format that I have commented.
I honestly don't know if there is a better way to save in MongoDB, but the idea is to save my Array of objects and each object is a document.
It seems to me that if you want your array to be of objects, you should create the elements like that, objects . You are adding them as
string
.So, in the part of your code where you add these elements, you could try something like this: