How to query in mongodb programmatically? - json

I wannt to create code like this:
var result = Attributes.find({
attribute_name : {
$exist : true,
$in : [1]
}
});
but programmatically, so i ceate code like this:
var genQuery = '{ "' + by + '" : { "$exists" : true, "$in" : [' + data + ']} }';
var result = Attributes.find(genQuery);
but I get error maximum call stack
because result of JSON.parse(genQuery)
{ _id: { '$exists': true, '$in': [ 1 ] } }
How to query in mongodb programmatically?

Your genQuery variable you declare is a String, but you cannot pass strings as selectors or modifiers in find() functions.
You should create an Object to make it works:
var genQuery = {};
//use this notation to declare a new object key depending on a variable
genQuery[by] = {
$exists: true,
$in: [1]
};
var result = Attributes.find(genQuery);

Related

Accessing json returning undefined react js

I am trying to grab some json data to display in Ui but when I iterate over it using the map method I keep getting undefined.Any help will be really appreciated.Here is a link on code sandbox https://codesandbox.io/s/late-wood-kx8w2?file=/src/App.js
This line
const [items, setItem] = useState(Object.keys(trees));
is passing the tree keys to the View function and not the actual data. I believe that you meant to pass the data. Your code passes 'name' and 'children' as {items} that then gets displayed by View.js.
The following code shows you how you can parse the tree and get the names and the values. It's incomplete, but it should give you a start on how to do the traversal.
import React, { useState } from "react";
export default function Start(){
const trees = {
name: "root",
children: [
{
name: "child1",
children: [
{ name: "child1-child1", data: "c1-c1 Hello" },
{ name: "child1-child2", data: "c1-c2 JS" }
]
},
{ name: "child2", data: "c2 World" }
]
};
const treesCopy = trees;
function Traverse(tree){
var treesCopy = tree;
var str = [];
for (var prop in treesCopy) {
console.log(prop);
if (prop=="children"){
str = str + "name: "+ prop + ",";
treesCopy = treesCopy[prop][0];
// console.log('New tree: ',treesCopy);
return str + Traverse(treesCopy);
}
str = str + "name: "+ prop +" value: " + treesCopy[prop]+",";
}
return str;
};
const str = Traverse(treesCopy);
return(
<>
{
str ? str.split(",").map(place => <p> {place} </p>)
: ""
}
</>
)
}

Create JSON using for loop, Express.js

I'm newbie to express.js. I want to create a JSON using for loop. But the code returns object object. I don't know why. But for a single JSON, it returns as a JSON value. In this code, I have added a function to retrieve my JSON values from mongoDB. Please help me to complete this.
router.get('/', (req, res) => {
Followups.find({}).then(followupData => {
Staffs.find({}).then(staffData => {
Institutions.find({}).then(institutionData => {
var fcount = Object.keys(followupData).length;
var scount = Object.keys(staffData).length;
var icount = Object.keys(institutionData).length;
console.log(icount);
var jsonData = '';
function getStaffData(id) {
return staffData.filter(
function(staffData) {
return staffData._id == id;
}
);
}
function getInstitutionData(id) {
return institutionData.filter(
function(institutionData) {
return institutionData._id == id;
}
);
}
for (i=0; i<fcount; i++)
{
fstaffid = followupData[i].staffid;
fschoolid = followupData[i].schoolid;
staffDetails = getStaffData(fstaffid);
institutionDetails = getInstitutionData(fschoolid);
jsonData += {
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
}
}
console.log(jsonData);
res.render('followup', {followupData:followupData, jsonData: jsonData});
});
});
});
});
Problem solved by using concat
jsonData = jsonData.concat({
followupid : followupData[i]._id,
schoolid : followupData[i].schoolid,
staffid : followupData[i].staffid,
staffname : staffDetails[0].achternaam + ' ' + staffDetails[0].voornaam + ' ' + staffDetails[0].tv,
staffplace : staffDetails[0].plaats,
staffphone : staffDetails[0].telefoon,
schoolname : institutionDetails[0].instellingsnaam,
schoolplace : institutionDetails[0].plaatsnaam,
schoolphone : institutionDetails[0].telefoonnummer,
notes : followupData[i].notes,
date : followupData[i].date,
created_at : followupData[i].created_at,
status : followupData[i].seen
});
You can display the data of jsonData like:
console.log(JSON.stringify(jsonData));
object object means jsonData is a JSON object, you cannot display a JSON object directly. You must stringify it before doing this.
You may be able to find more about the issue after using JSON.stringify

findding a key in an object in node.js

i have a lookup-table of JSON, i want to search for a specific key in that lookup-table; which could return me the complete object of the match.
Is it possible without any loop or with any built-in liberary.
its JSON, a straight look up for the key.?
var obj = { 'foo' : 'bar', 'fez' : [1,2,3], 'fizz' : { 'baz': true} };
console.log( "'foo' is accessed like " + obj.foo + " -or- " + obj['foo'] )
var fw_table = {"FW_1":{ "tn":"sn_201", "cf": "06.57", "ci": "A1", "di":"048"}, "FW_2":{ "tn":"sn_202", "cf": "06.57", "ci": "A2", "di":"045"}};
function search(fwObj, key, val){
var topKey = Object.keys(fwObj).find((e)=>{ return(fwObj[e][key] === val ) });
console.log(topKey);
return fwObj[topKey];
}
console.log("Find cf:'06.57' : ", search(fw_table, "cf","06.57") );
console.log("Find di:'045' : ", search(fw_table, "di","045") );

Read csv to object of object for d3 [datamaps]

I'm using datamaps and would like to be able to read the data from a csv file.
The data format that datamaps is expecting is the following:
var loadeddata = {
"JPN":{Rate:17.5,fillKey:"firstCat"},
"DNK":{Rate:16.6,fillKey:"secondCat"}
};
I would like to read a csv file of the following structure and transform it into the format that datamaps is expecting:
ISO, Rate, fillKey
JPN, 17.5, firstCat
DNK, 16.6, secondCat
My 'best attempt' was using the following code:
var csvloadeddata;
d3.csv("simpledata.csv", function (error, csv) {
if (error) return console.log("there was an error loading the csv: " + error);
console.log("there are " + csv.length + " elements in my csv set");
var nestFunction = d3.nest().key(function(d){return d.ISO;});
csvloadeddata = nestFunction.entries(
csv.map(function(d){
d.Rate = +d.Rate;
d.fillKey = d.fillKey;
return d;
})
);
console.log("there are " + csvloadeddata.length + " elements in my data");
});
But this code generates a variable 'csvloadeddata' that looks like this:
var csvloadeddata = [
{"key": "JPN", "values": { 0: {Rate:17.5, fillKey:"firstCat"}} },
{"key": "DNK", values : { 1: {Rate:16.6,fillKey:"secondCat"}} }
];
What am I doing wrong?
Found the answer myself. If somebody is interested – this is what I ended up using:
<script>
d3.csv("simpledata.csv", function(error, csvdata1) {
globalcsvdata1 = csvdata1;
for (var i=0;i<csvdata1.length;i++)
{
globalcsvdata1[ globalcsvdata1[i].ISO] = globalcsvdata1[i] ;
//console.log(globalcsvdata1[i]);
delete globalcsvdata1[i].ISO;
delete globalcsvdata1[i] ;
}
myMap.updateChoropleth(globalcsvdata1);
}
);
var myMap = new Datamap({
element: document.getElementById('map'),
scope: 'world',
geographyConfig: {
popupOnHover: true,
highlightOnHover: false
},
fills: {
'AA': '#1f77b4',
'BB': '#9467bd',
defaultFill: 'grey'
}
});
</script>
</body>
The csv has the following structure:
ISO,fillKey
RUS,AA
USA,BB
Here is a working example: http://www.explainingprogress.com/wp-content/uploads/datamaps/uploaded_gdpPerCapita2011_PWTrgdpe/gdpPerCapita2011_PWTrgdpe.html

Loop to add data to complex JSON object

I have a complex JSON Object like this:
var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {
CustomerID: 400, CustomerName: "John"
} }
] } ] };
I am trying to do two things:
Declare this object but with the variable data empty
With a loop, add items dynamically to the data object,
How can I do it?
This isn't too complex an object. And it isn't JSON until it's converted into a string.
Right now, it's just plain-ol' JS objects and arrays.
Breaking that down into its elements might look like this:
var requestData = {};
requestData.__batchRequests = [];
requestData.__batchRequests[0] = {};
requestData.__batchRequests[0].__changeRequests = [];
requestData.__batchRequests[0].__changeRequests[0] = {};
requestData.__batchRequests[0].__changeRequests[0].requestUri = "Customers";
requestData.__batchRequests[0].__changeRequests[0].method = "POST";
requestData.__batchRequests[0].__changeRequests[0].headers = { "Content-ID" : "1" };
requestData.__batchRequests[0].__changeRequests[0].data = {};
Aside from the repeats, what do you see?
Personally, I see that __changeRequests[0] is an object as simple as:
var changeRequest = {
requestUri : "Customers",
method : "POST",
headers : { "Content-ID" : "1" },
data : {}
};
I also see that I can just push that onto my array of change requests:
requestData.__batchRequests[0].__changeRequests.push(changeRequest);
Right?
I also know that my changeRequest variable still points to the one that I just added to the array, and whatever I change on the object will show up as changed in the array's reference to the object, too:
changeRequest.data.CustomerName = "Bob";
changeRequest.data.CustomerID = "204";
requestData.__/*...*/changeRequests[0].data.CustomerName; // Bob
So how about writing yourself some helper-functions?
function extend (obj, additions) {
var key;
for (key in obj) { if (additions.hasOwnProperty(key)) {
obj[key] = additions[key];
}
}
function makeChangeRequest (url, method, headers, data) {
var request = {
requestUri : url,
method : method,
headers : {},
data : {}
};
extend(request.headers, headers);
extend(request.data, data);
return request;
}
function getBatch (num) { return requestData.__batchRequests[num]; }
var changeReq = makeChangeRequest("Customers",
"POST",
{ "Content-ID" : "1" },
{ CustomerName : "Bob", CustomerID : "2012" });
var batch = getBatch(0);
batch.__changeRequests.push(changeReq);
If you want to add more data to changeReq.data later:
extend(changeReq.data, { Address : "33 Nowhere Rd.", City : "Splitsville" });
For the first part of your question, you can initialize data with an empty associative array:
var requestData = { __batchRequests: [ { __changeRequests: [
{ requestUri: "Customers", method: "POST", headers: { "Content-ID": "1" }, data: {} }
] } ] };
This next part assumes, perhaps incorrectly, that you can use jQuery. It also assumes that you have an array containing all of the relevant key value pairs.
var customerDeetsArray =[{CustomerID: 400}, {CustomerName: "John"}];
for (var i in customerDeetsArray) {
requestData.data = $.extend(requestData.data, customerDeetsArray[i]);
}
See working example which makes use of console.debug:
http://jsfiddle.net/4Rh72/6/