Approaching JSON data returns 'undefined' - node.js

When I accessing "dept_name", the JSON returns 'undefined'.
How can I return correct output?
JSON object (content) from an API
"departments": [
{
"dept_no": "d005",
"dept_name": "Development",
"from_date": "1994-07-03",
"to_date": "9999-01-01",
"dept_manager": [
{
"emp_no": 110511,
"first_name": "DeForest",
"last_name": "Hagimont",
"email": "110511#cloud-spartan.com",
"from_date": "1985-01-01",
"to_date": "1992-04-25"
},
{
"emp_no": 110567,
"first_name": "Leon",
"last_name": "DasSarma",
"email": "110567#cloud-spartan.com",
"from_date": "1992-04-25",
"to_date": "9999-01-01"
}
]
}
],
when I accessing data['departments'].dept_no returns 'undefined'
var content_depart = content['departments'];
console.log(content_depart);
var department = content_depart.dept_name;
console.log(department);
console.log(content_depart)
[ { dept_no: 'd005',
dept_name: 'Development',
from_date: '1994-07-03',
to_date: '9999-01-01',
dept_manager: [ [Object], [Object] ] } ]
console.log(department)
undefined

data['departments'] is an array.
let data =
{ // v--------- array !
"departments": [
{ // ...
You can't access its members directly, but have to specify the index first. In example :
let data = {"departments":[{"dept_no":"d005","dept_name":"Development","from_date":"1994-07-03","to_date":"9999-01-01","dept_manager":[{"emp_no":110511,"first_name":"DeForest","last_name":"Hagimont","email":"110511#cloud-spartan.com","from_date":"1985-01-01","to_date":"1992-04-25"},{"emp_no":110567,"first_name":"Leon","last_name":"DasSarma","email":"110567#cloud-spartan.com","from_date":"1992-04-25","to_date":"9999-01-01"}]}]};
console.log(data.departments[0].dept_no);

Add index before accessing data
var department = content_depart[0].dept_name;
console.log(department);

content_depart is array not an object
so go with content_depart[0].dept_name

Related

Retrieve a specific level level from a JSON object in Node.js

I have a two level JSON
{"Policy": {
"Channel": "online",
"Credit Score": "20000",
"Car": [{
"Age": "28",
"AnnualMiles": "15000",
"CarAge": "3",
"Young Driver": "1"
}
]
}}
i am trying to change the json structure and only retrieve the root policy object from the JSON
let data = JSON.parse(json);
console.log(data)
policy=data.Policy
console.log(policy)
The output that i am getting is the entire JSON basically, the result that i want is just the root level values :
{
"Channel": "online",
"Credit Score": "20000"
}
How do i only retrieve the root level in nodejs?
var json = {"Policy": {
"Channel": "online",
"Credit Score": "20000",
"Car": [{
"Age": "28",
"AnnualMiles": "15000",
"CarAge": "3",
"Young Driver": "1"
}
]
}}
//Filter function for objects
Object.filter = (obj, predicate) =>
Object.keys(obj)
.filter( key => predicate(obj[key]) )
.reduce( (res, key) => (res[key] = obj[key], res), {} );
//Exclude objects
let result = Object.filter(json.Policy, x => typeof x != "object")
console.log(result)
Output:
{
Channel: "online",
Credit Score: "20000"
}

Not able to query for nested relations using dgraph-orm

I am using dgraph-orm for fetching nested relational values but it works for single level but not multiple level.
I am getting the page details but unable to fetch the avatar of the page.
Here is my snippet:
let posts = await PagePost.has('page_id', {
filter: {
page_id: {
uid_in: [page_id]
}
},
include: {
page_id: {
as: 'page',
include: {
avatar: {
as: 'avatar'
}
}
},
owner_id: {
as: 'postedBy'
}
},
order: [], // accepts order like the above example
first: perPage, // accepts first
offset: offset, // accepts offset
});
I am not getting avatar for the attribute page_id:
{
"uid": "0x75b4",
"title": "",
"content": "haha",
"created_at": "2019-09-23T08:50:52.957Z",
"status": true,
"page": [
{
"uid": "0x75ac",
"name": "Saregamaapaaaa...",
"description": "This a is place where you can listen ti thrilling music.",
"created_at": "2019-09-23T06:46:50.756Z",
"status": true
}
],
"postedBy": [
{
"uid": "0x3",
"first_name": "Mohit",
"last_name": "Talwar",
"created_at": "2019-07-11T11:37:33.853Z",
"status": true
}
]
}
Is there a support for multilevel field querying in the orm??
There was some issue with ORM itself it was not able to recognize the correct model name for multilevel includes and generating the wrong queries.
Fixed the same in version 1.2.4, please run npm update dgraph-orm --save to update your DgraphORM.
Thanks for the issue.

REST API using Nodejs Mongoose Express

{
"_id": "58be5a4a031372098578b1d6",
"name": "A",
"email": "abc#gmail.com",
"username": "A.a",
"password": "$2a$05$GAF1hP91EowKUTKr14ASL.MRd2lOjotfOgVlEghwnqctNcIe5seNW",
"latitude": 12,
"longitude": 72,
"profilePic": "images/A.png",
"__v": 9,
"isBuddyEnabled": true,
"friendRequests": [
{
"friendId": "58be7aa0c204cb134068975d",
"isAccepted": true
},
{
"friendId": "58bf8cb4c26d5811b188a600",
"isAccepted": false
}
],
"friends": [
"58be7aa0c204cb134068975d"
],
"networkContacts": [
{
"profession": "doctor"
}
],
"interests": [
"sports",
"music"
]
}
I have the above json for a single user , now i need the array of such json with all info whose friendRequest isAccepted is false which means these requests are pending for him,
for eg: when i hit api/requests/58be5a4a031372098578b1d6 => i have to get info of id 58bf8cb4c26d5811b188a600
till now i was able to retreive the ids whose request was not accepted via following query
app.post('/api/users/requests/:id'function(req,res){User.find({"_id":req.params.id})
.find({"friendRequests.isAccepted":false},function(err,callback){}})
You can use array filter to pop out the subdocument in array based on the filter
User.find({"_id":req.params.id}, function (err, user) {
var friendRequests = user.friendRequests.filter(function (fr) {
return fr.isAccepted == false;
}).pop();
console.log(friendRequests); //logs { "friendId": "58bf8cb4c26d5811b188a600", "isAccepted": false
});

Count objects in array in an object in Frisby

I am starting to learn FrisbyJS and trying to create some assertions.
I get an json that looks like this
[
{
"articles": [
{
"article": "123-123002",
"updated": "2016-10-20T14:57:25",
"sourced balance": [],
"balance": "50.00"
},
{
"article": "100-123001",
"updated": "2016-10-20T14:41:36",
"sourced balance": [],
"balance": "10.00"
}
],
"DistrictID": [],
"WarehouseID": "SebastiansWarehouse",
"SourceID": "1234",
"City": "Stockholm",
"WarehouseName": "Sebastians Warehouse",
"WarehouseType": "STORE"
}
]
And I want to:
1. count the number of article objects
2. verify that the number X in articles array has a variable with value "123-123002"
How can I do this in Frisby?
My code currently is:
var frisby = require('frisby');
frisby.create('Mekonomen RIF1')
.get('https://10.254.8.67:9443/INTERSHOP/rest/WFS/Mekonomen-MekB2BSE-Site/-/availability/sources/1234/warehouses/SebastiansWarehouse/products/',{ strictSSL: false})
.expectStatus(200)
.expectHeaderContains('content-type', 'application/json')
.expectJSON('?',{
articles: [],
DistrictID: [],
WarehouseID: "SebastiansWarehouse",
SourceID: '1234',
City: "Stockholm",
WarehouseName: "Sebastians Warehouse",
WarehouseType: "STORE"
}
)
.expectJSON('?.articles',{
articles: [],
DistrictID: [],
WarehouseID: "SebastiansWarehouse",
SourceID: '1234',
City: "Stockholm",
WarehouseName: "Sebastians Warehouse",
WarehouseType: "STORE"
}
)
.expectMaxResponseTime(500)
.toss();
you can include
.afterJSON(json){
//json.articles can be asserted here
//some more assertion on the response
}
which will parse the response and send it as an argument which can be asserted using simple javascript conditions, statements, loops etc.

find object inside JSON using nested ID

i have a mongo collection like this
{"stores": [{"name": "foo",
"songs": [ {"id": "", "name": "", "artist": "", "category": "", "tags": []} ],
"songsSchedule": [
{
"song_id": "",
"date": ,
"user": "",
"help": ,
"partners": [{"user": ""}],
"likes":
}
]
}]}
and i want to get the songs name and artist from the songsSchedule song_id, i've tried this but it's not working
var query = { _id: fn.generateID(req.params.store_id), songsSchedule: { $exists: true } };
var select = { songsSchedule:1 };
var array = [];
client("stores", function(err, collection) {
if (err)
return res.json(fn.status("30"));
collection.findOne(query, select, function(err, store) {
if (err || !store)
return res.json(fn.status("31"));
for (var i in store.songsSchedule) {
var song = store.songsSchedule[i];
array.push(song.song_id);
}
collection.find({ _id: fn.generateID(req.params.store_id), "songs._id": { $in: array } }, function(err, songs) {
res.json(songs);
});
});
});
and i dont really know if it's the best way of doing it
I'm not entirely clear what you mean by "get the songs name and artist from the songsSchedule song_id" but it looks like that query will be messy.
If it were me, I'd consider splitting out songs and songSchedule into their own collections for easier querying.
from your document example, the "songs" field contains documents that do not contain an "_id" field.
"songs": [ {"name": "", "artist": "", "category": "", "tags": []} ]
But, your find() query is querying on the "songs._id" field.
Also, I'm not too familiar with the json() method, but does it handle cursors?
Regards,
Kay

Resources