Related
I am trying to get gas prices for a web app I am making. I found a web scraper from Apify that gets the data I need. The problem is I'm not sure how to extract just the gas prices from the returned object from the API. There is a lot of information.
Here is the code I run in node:
import { ApifyClient } from 'apify-client';
// Initialize the ApifyClient with API token
const client = new ApifyClient({
token: 'apify_api_********',
});
// Prepare actor input
const input = {
"location": "Indiana",
"maxCrawledPlacesPerSearch": 1
};
(async () => {
// Run the actor and wait for it to finish
const run = await client.actor("natasha.lekh/gas-prices-scraper").call(input);
// Fetch and print actor results from the run's dataset (if any)
console.log('Results from dataset');
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
console.log(item);
})();
Which returns:
Results from dataset
{
title: 'Luke',
subTitle: null,
description: null,
price: null,
menu: null,
categoryName: 'Gas station',
address: '1051 Indianapolis Blvd, Hammond, IN 46320',
locatedIn: null,
neighborhood: '1051 Indianapolis Blvd',
street: '1051 Indianapolis Blvd',
city: 'Hammond',
postalCode: '46320',
state: 'Indiana',
countryCode: 'US',
plusCode: 'MFVP+R3 Hammond, Indiana',
website: 'http://uluke.com/',
phone: '(219) 473-1425',
temporarilyClosed: false,
claimThisBusiness: false,
location: { lat: 41.6945038, lng: -87.5147858 },
permanentlyClosed: false,
totalScore: 3.7,
isAdvertisement: false,
rank: 1,
placeId: 'ChIJm_BHBfbYEYgRZee8gFZeG7o',
categories: [ 'Gas station', 'Convenience store' ],
cid: '13410416041045845861',
url: 'https://www.google.com/maps/place/Luke/#41.6945038,-87.5147858,17z/data=!3m1!4b1!4m6!3m5!1s0x8811d8f60547f09b:0xba1b5e5680bce765!8m2!3d41.6945038!4d-87.5147858!16s%2Fg%2F1ptvtxy1r?hl=en',
searchPageUrl: 'https://www.google.com/maps/search/gas%20station%20in%20Indiana?hl=en',
searchPageLoadedUrl: 'https://www.google.com/maps/search/gas+station+in+Indiana/#40.7310665,-86.5930181,8z?hl=en',
searchString: 'gas station in Indiana',
scrapedAt: '2023-02-11T04:17:35.902Z',
popularTimesLiveText: null,
popularTimesLivePercent: null,
popularTimesHistogram: {
Su: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object]
],
Mo: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object]
],
Tu: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object]
],
We: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object]
],
Th: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object]
],
Fr: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object]
],
Sa: [
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object],
[Object], [Object], [Object]
]
},
openingHours: [
{ day: 'Monday', hours: '5 AM to 10 PM' },
{ day: 'Tuesday', hours: '5 AM to 10 PM' },
{ day: 'Wednesday', hours: '5 AM to 10 PM' },
{ day: 'Thursday', hours: '5 AM to 10 PM' },
{ day: 'Friday', hours: '5 AM to 10 PM' },
{ day: 'Saturday', hours: '5 AM to 10 PM' },
{ day: 'Sunday', hours: '5 AM to 10 PM' }
],
peopleAlsoSearch: [
{
category: 'People also search for',
title: 'BP Luke Gas Station',
reviewsCount: 441,
totalScore: 3.3
},
{
category: 'People also search for',
title: 'Luke Gas Station Car Wash',
reviewsCount: 9,
totalScore: 2.2
},
{
category: 'People also search for',
title: 'GoLo',
reviewsCount: 331,
totalScore: 3.8
},
{
category: 'People also search for',
title: 'Shell',
reviewsCount: 104,
totalScore: 3.5
},
{
category: 'People also search for',
title: "Luke's Gas Station",
reviewsCount: 0,
totalScore: 0
}
],
additionalInfo: {
Accessibility: [ [Object], [Object] ],
Offerings: [ [Object] ],
Amenities: [ [Object] ],
Payments: [ [Object] ]
},
reviewsCount: 283,
reviewsDistribution: {
oneStar: 41,
twoStar: 10,
threeStar: 51,
fourStar: 67,
fiveStar: 114
},
imagesCount: 8,
reviews: [],
reviewsTags: [
{ title: 'prices', count: 21 },
{ title: 'pumps', count: 15 },
{ title: 'clean', count: 8 },
{ title: 'pay', count: 6 },
{ title: 'credit cards', count: 5 },
{ title: 'convenient', count: 3 }
],
orderBy: [],
gasPrices: [
{
priceTag: '$3.30',
updatedAt: '2023-02-10T14:46:30.000Z',
unit: 'gallon',
currency: 'USD',
price: 3.3,
gasType: 'Regular'
},
{
priceTag: '$3.70',
updatedAt: '2023-02-10T05:37:40.000Z',
unit: 'gallon',
currency: 'USD',
price: 3.7,
gasType: 'Midgrade'
},
{
priceTag: '$4.10',
updatedAt: '2023-02-10T05:37:40.000Z',
unit: 'gallon',
currency: 'USD',
price: 4.1,
gasType: 'Premium'
},
{
priceTag: '$5.00',
updatedAt: '2023-02-10T06:52:21.000Z',
unit: 'gallon',
currency: 'USD',
price: 5,
gasType: 'Diesel'
}
]
}
All I want is the last bit, the priceTag and gasType for each type of gas. How would I get that data out of the returned object?
I thought it was a JSON file so I tried a few things I found online, but I'm not really sure where to start.
I'm receiving an array and performing a treatment to extract some information.
When I get the matrix like this, everything goes well!
[
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object]
]
},
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object]
]
}
]
But when the array comes like this:
[
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
{ averages: 'No data in period.' }
]
I get this error:
ccs.medias.forEach is not a function
Could this be the error?
{ averages: 'No data in period.' }
The code mentioned to filter the information I want is this:
function test(arr) {
let results = [];
arr.forEach(ccs => {
ccs.medias.forEach(element => {
if (element["TYPE"] === 'AAA') {
results.push(element["STATUS"])
}
})
})
return results;
}
As I mentioned above, this code works for the first array example, but not for the following one.
I appreciate if anyone can help me analyze it!
Yep, you guessed right, problem is here:
{ averages: 'No data in period.' }
Before using .forEach(), you need to make sure property value (ccs.averages) is array, so just add simple if-condition like:
if (Array.isArray(ccs.averages)) {
// Do what you need with array and only
}
Full code:
const arr = [
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
{
averages: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
{ averages: 'No data in period.' }
]
function test(arr) {
let results = [];
arr.forEach(ccs => {
// Make sure .avarages is array
if (Array.isArray(ccs.averages)) {
ccs.averages.forEach(element => {
if (element["TYPE"] === 'AAA') {
results.push(element["STATUS"])
}
})
}
})
return results;
}
console.log(test(arr));
Refs: Array.isArray().
As this question is tagged as "mongo", to do it in a query and retrieve results directly without the fields which are not an array you can use one of these queries:
For a find query you can add:
"averages": { "$type": "array }
Like this:
db.collection.find({
"averages": {
"$type": "array"
}
})
Example here
Also if you are using an aggregation stage you can add a $match stage like this:
db.collection.aggregate([
{
"$match": {
"averages": {
"$type": "array"
}
}
}
])
Example here
Note that the queries use $type
In this way you can avoid the loop.
To begin i'm making two queries to a mongodb database, as showed below
let getLevelsZones = async () => {
today = yyyy + '-' + mm + '-' + dd + ' ' + '23:00:00.000Z';
yesterday = yyyy_y + '-' + mm_y + '-' + dd_y + ' ' + '00:00:00.000Z';
return LevelsZonesModel.find({
building:"5ef076a507f9cc56cb8d957d",
$and:[
{date_created: {$gte: yesterday}},
{date_created: {$lt: today}}
]
});
}
let getLevelsByZoneAndUtility = async (zone, utility) => {
return LevelsZonesModel.find({
building:"5ef076a507f9cc56cb8d957d",
utility: utility,
zone: zone,
$and:[
{date_created: {$gte: yesterday}},
{date_created: {$lt: today}}
]
})
}
Both queries are executed on the same collection, but the second query needs data from the first query to be executed later in the code (below).
let levels_zones = await getLevelsZones();
levels_zones.map(async (level_zone, i) => {
let levels_zone_utility = await getLevelsByZoneAndUtility(level_zone.zone, level_zone.utility);
console.log(levels_zone_utility);
First i'm going through all the documents so I can use "level_zone" to manipulate the results but before that I use it a parameter for the second query and print it to the screen to test if it goes as i want.
Here's a part of the output needed to explain my problem
[
{
_id: 60bc054427adeb5f5fc8160e,
building: '5ef076a507f9cc56cb8d957d',
date: 2021-06-05T23:00:00.000Z,
utility: 'agua-potavel',
zone: 'east-building',
__v: 0,
date_created: 2021-06-06T22:49:18.251Z,
date_modified: 2021-06-06T22:49:18.251Z,
hours: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object],
'13': [Object],
'14': [Object],
'15': [Object],
'16': [Object],
'17': [Object],
'18': [Object],
'19': [Object],
'20': [Object],
'21': [Object],
'22': [Object],
'23': [Object]
},
metrics: { m3: 0.020000000000038654, cost_m3: 0.06919000000013371 },
sources: { '5ef0e45607f9cc56cb8d9689': [Object] }
},
{
_id: 60bd5afd27adeb5f5f18ae33,
building: '5ef076a507f9cc56cb8d957d',
date: 2021-06-06T23:00:00.000Z,
utility: 'agua-potavel',
zone: 'east-building',
__v: 0,
date_created: 2021-06-07T18:08:12.660Z,
date_modified: 2021-06-07T18:08:12.660Z,
hours: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object],
'13': [Object],
'14': [Object],
'15': [Object],
'16': [Object],
'17': [Object],
'18': [Object],
'19': [Object]
},
metrics: { m3: 4.930000000000007, cost_m3: 17.055335000000024 },
sources: { '5ef0e45607f9cc56cb8d9689': [Object] }
}
]
[
{
_id: 60bc054427adeb5f5fc8160e,
building: '5ef076a507f9cc56cb8d957d',
date: 2021-06-05T23:00:00.000Z,
utility: 'agua-potavel',
zone: 'east-building',
__v: 0,
date_created: 2021-06-06T22:49:18.251Z,
date_modified: 2021-06-06T22:49:18.251Z,
hours: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object],
'13': [Object],
'14': [Object],
'15': [Object],
'16': [Object],
'17': [Object],
'18': [Object],
'19': [Object],
'20': [Object],
'21': [Object],
'22': [Object],
'23': [Object]
},
metrics: { m3: 0.020000000000038654, cost_m3: 0.06919000000013371 },
sources: { '5ef0e45607f9cc56cb8d9689': [Object] }
},
{
_id: 60bd5afd27adeb5f5f18ae33,
building: '5ef076a507f9cc56cb8d957d',
date: 2021-06-06T23:00:00.000Z,
utility: 'agua-potavel',
zone: 'east-building',
__v: 0,
date_created: 2021-06-07T18:08:12.660Z,
date_modified: 2021-06-07T18:08:12.660Z,
hours: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object],
'13': [Object],
'14': [Object],
'15': [Object],
'16': [Object],
'17': [Object],
'18': [Object],
'19': [Object]
},
metrics: { m3: 4.930000000000007, cost_m3: 17.055335000000024 },
sources: { '5ef0e45607f9cc56cb8d9689': [Object] }
}
]
As you can see there's two arrays each one with two objets, that's I want to see but the problem is that both arrays are the same, so i'm getting duplicate results somehow and I'm struggling so hard to fix that. Just so you have an idea, the entire output is supposed to have 22 arrays each one with 2 objects, instead it has 44 arrays with the same amount of objects. I hope you can help me find a way to fix. Thank you.
EDIT: Here's an example (to clarify things) of what the query should return, assuming I choose a specific zone and utility as an example, but that's what should be returned for every zone and utility
Query in Robo 3T
Looking your data, your problem seems that you have duplicated data with the same 'utility' and 'zone' values. Look at:
{
_id: 60bc054427adeb5f5fc8160e,
building: '5ef076a507f9cc56cb8d957d',
date: 2021-06-05T23:00:00.000Z,
utility: 'agua-potavel',
zone: 'east-building',
__v: 0,
date_created: 2021-06-06T22:49:18.251Z,
date_modified: 2021-06-06T22:49:18.251Z,
hours: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object],
'13': [Object],
'14': [Object],
'15': [Object],
'16': [Object],
'17': [Object],
'18': [Object],
'19': [Object],
'20': [Object],
'21': [Object],
'22': [Object],
'23': [Object]
},
metrics: { m3: 0.020000000000038654, cost_m3: 0.06919000000013371 },
sources: { '5ef0e45607f9cc56cb8d9689': [Object] }
}
{
_id: 60bd5afd27adeb5f5f18ae33,
building: '5ef076a507f9cc56cb8d957d',
date: 2021-06-06T23:00:00.000Z,
utility: 'agua-potavel',
zone: 'east-building',
__v: 0,
date_created: 2021-06-07T18:08:12.660Z,
date_modified: 2021-06-07T18:08:12.660Z,
hours: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object],
'13': [Object],
'14': [Object],
'15': [Object],
'16': [Object],
'17': [Object],
'18': [Object],
'19': [Object]
},
metrics: { m3: 4.930000000000007, cost_m3: 17.055335000000024 },
sources: { '5ef0e45607f9cc56cb8d9689': [Object] }
}
Because each one of them belongs to LevelsZonesModel, you will iterate for both 60bc054427adeb5f5fc8160e and 60bd5afd27adeb5f5f18ae33. Because they have the same value, they made the same query to getLevelsByZoneAndUtility, with values (east-building, agua-potavel), which will give you the same result
[
{
_id: 60bc054427adeb5f5fc8160e,
building: '5ef076a507f9cc56cb8d957d',
date: 2021-06-05T23:00:00.000Z,
utility: 'agua-potavel',
zone: 'east-building',
__v: 0,
date_created: 2021-06-06T22:49:18.251Z,
date_modified: 2021-06-06T22:49:18.251Z,
hours: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object],
'13': [Object],
'14': [Object],
'15': [Object],
'16': [Object],
'17': [Object],
'18': [Object],
'19': [Object],
'20': [Object],
'21': [Object],
'22': [Object],
'23': [Object]
},
metrics: { m3: 0.020000000000038654, cost_m3: 0.06919000000013371 },
sources: { '5ef0e45607f9cc56cb8d9689': [Object] }
},
{
_id: 60bd5afd27adeb5f5f18ae33,
building: '5ef076a507f9cc56cb8d957d',
date: 2021-06-06T23:00:00.000Z,
utility: 'agua-potavel',
zone: 'east-building',
__v: 0,
date_created: 2021-06-07T18:08:12.660Z,
date_modified: 2021-06-07T18:08:12.660Z,
hours: {
'0': [Object],
'1': [Object],
'2': [Object],
'3': [Object],
'4': [Object],
'5': [Object],
'6': [Object],
'7': [Object],
'8': [Object],
'9': [Object],
'10': [Object],
'11': [Object],
'12': [Object],
'13': [Object],
'14': [Object],
'15': [Object],
'16': [Object],
'17': [Object],
'18': [Object],
'19': [Object]
},
metrics: { m3: 4.930000000000007, cost_m3: 17.055335000000024 },
sources: { '5ef0e45607f9cc56cb8d9689': [Object] }
}
]
So you have one array related to the query of element id 60bc054427adeb5f5fc8160e, and other array for the query of element id 60bd5afd27adeb5f5f18ae33, which are the same query, and because of that, the same result.
So that's the reason of results being duplicated. If they were 3 documents with the same utility and zone, you will have tripled data, and so on.
when hitting a get route, I get the data I am expecting but it looks like my route is hit TWICE: once with data, and another time with no info supplied.
if I navigate to a URL: https://www.something.com/events/XYZ then I get all the data and the page is populated properly. The page never seems to finish loading unless I click on the "X" in the browser.
app.get("/events/:id", function(req, res){
Event.findById(req.params.id, function (err, foundEvent){
if(err){
console.log("beginning error");
console.log(err);
console.log("found this event: " + foundEvent);
console.log("ending error");
}else {
console.log("now entering normal loop");
console.log(foundEvent);
res.render("showevent", {event: foundEvent});
}
})
});
When I type in a URL (copy/paste), I get the following (lengthy, sorry, not sure which part may be relevant) console.log:
now entering normal loop
{ _id: 5cf30944e75f2679f77287a2,
name: 'Memorial Day 2019',
date: 2019-06-01T23:24:52.063Z,
story: 'Memorial Day parade and Ceremony',
posts: [ { link: [Array], image: [], _id: 5cf30944e75f2679f77287a3 } ],
__v: 0 }
beginning error
{ CastError: Cast to ObjectId failed for value "main.js" at path "_id" for model "Event"
at new CastError (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/error/cast.js:29:11)
at ObjectId.cast (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/schema/objectid.js:242:11)
at ObjectId.SchemaType.applySetters (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/schematype.js:892:12)
at ObjectId.SchemaType._castForQuery (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/schematype.js:1304:15)
at ObjectId.SchemaType.castForQuery (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/schematype.js:1294:15)
at ObjectId.SchemaType.castForQueryWrapper (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/schematype.js:1273:15)
at cast (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/cast.js:307:32)
at model.Query.Query.cast (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/query.js:4529:12)
at model.Query.Query._castConditions (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/query.js:1762:10)
at model.Query.<anonymous> (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/query.js:2015:8)
at model.Query._wrappedThunk [as _findOne] (/home/scott/cchistory/cchistory/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
at process.nextTick (/home/scott/cchistory/cchistory/node_modules/kareem/index.js:369:33)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
message: 'Cast to ObjectId failed for value "main.js" at path "_id" for model "Event"',
name: 'CastError',
stringValue: '"main.js"',
kind: 'ObjectId',
value: 'main.js',
path: '_id',
reason: undefined,
model:
{ [Function: model]
hooks: Kareem { _pres: [Object], _posts: [Object] },
base:
Mongoose {
connections: [Array],
models: [Object],
modelSchemas: [Object],
options: [Object],
_pluralize: [Function: pluralize],
Schema: [Object],
model: [Function],
plugins: [Array] },
modelName: 'Event',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
options: null,
otherDbs: [],
relatedDbs: {},
states: [Object],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
plugins: [],
'$internalEmitter': [Object],
_listening: false,
_connectionOptions: [Object],
name: 'historydb',
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
client: [Object],
'$initialConnection': [Object],
db: [Object] },
discriminators: undefined,
events:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined },
'$appliedMethods': true,
'$appliedHooks': true,
_middleware: Kareem { _pres: [Object], _posts: [Object] },
'$__insertMany': [Function],
schema:
Schema {
obj: [Object],
paths: [Object],
aliases: {},
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
methodOptions: {},
statics: {},
tree: [Object],
query: {},
childSchemas: [Array],
plugins: [Array],
'$id': 6,
s: [Object],
_userProvidedOptions: {},
options: [Object],
'$globalPluginsApplied': true,
_requiredpaths: [] },
collection:
NativeCollection {
collection: [Object],
Promise: [Function: Promise],
opts: [Object],
name: 'events',
collectionName: 'events',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$init': Promise { [Circular] },
'$caught': true,
[Symbol(mongoose#Model)]: true } }
found this event: undefined
ending error
The "double whammy" was caused by a search bar that was on the page. With not info entered, it would hit the route with no info and cause the error.
I am moving the search function to a dedicated page for simplicity.
Thanks for the help folks!
I have integrated Neo4j in my NodeJS (backend) and Angular6 (front-end) application. My query runs and i get the data of nodes and connected node network in my Neo4j Browser. However, i want that entire data of nodes being displayed through a particular query on my console (i.e. in NodeJS -> back-end and angular ->front-end). This is not happening . I get only the first node data. Please help me retrieve the entire displayed nodal data in NodeJS .
NodeJS code
neo4j-controller.js
// Require Neo4j
var neo4j = require('neo4j-driver').v1;
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var express = require('express');
var router = express.Router();
var app = express();
const driver = new neo4j.driver("bolt://localhost:11001", neo4j.auth.basic("neo4j", "ib1"));
const cypher = 'MATCH (n) RETURN count(n) as count';
app.set('views', path.join(__dirname, 'views'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
var session = driver.session();
var request = require('request');
router.post('/', seekParameter);
module.exports = router;
//working code below
// ------------------------------- Original Code ----------------------------------------
function seekParameter(req, res) {
console.log("INSIDE NODE JS CONTROLLER OF seekParameter");
console.log("BODY IS ", req.body);
session
.run(`MATCH p=()-[r:Parameter]->() RETURN p`)
.then(function (result){
result.records.forEach(function(record){
console.log("record = ", record);
console.log("result = ", result)
console.log("1] record._fields[0].properties=",record._fields[0].properties);
res.send(record);
});
})
.catch(function(err){
console.log("inside catch = " + err);
})
session.close();
}
output
INSIDE NODE JS CONTROLLER OF seekParameter
BODY IS undefined
record = Record {
keys: [ 'p' ],
length: 1,
_fields:
[ Path { start: [Object], end: [Object], segments: [Array], length: 1 } ],
_fieldLookup: { p: 0 } }
result = { records:
[ Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] } ],
summary:
ResultSummary {
statement:
{ text: ' MATCH p=()-[r:Parameter]->() RETURN p ;',
parameters: {} },
statementType: 'r',
counters: StatementStatistics { _stats: [Object] },
updateStatistics: StatementStatistics { _stats: [Object] },
plan: false,
profile: false,
notifications: [],
server: ServerInfo { address: 'localhost:11001', version: 'Neo4j/3.4.7' },
resultConsumedAfter: Integer { low: 9, high: 0 },
resultAvailableAfter: Integer { low: 1, high: 0 } } }
1] record._fields[0].properties= { name: 'accidentTime' }
2]record._fields[1] = [ Path {
start: Node { identity: [Object], labels: [Array], properties: [Object] },
end: Node { identity: [Object], labels: [Array], properties: [Object] },
segments: [ [Object] ],
length: 1 } ]
record = Record {
keys: [ 'p' ],
length: 1,
_fields:
[ Path { start: [Object], end: [Object], segments: [Array], length: 1 } ],
_fieldLookup: { p: 0 } }
result = { records:
[ Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] },
Record {
keys: [Array],
length: 1,
_fields: [Array],
_fieldLookup: [Object] } ],
summary:
ResultSummary {
statement:
{ text: ' MATCH p=()-[r:Parameter]->() RETURN p ;',
parameters: {} },
statementType: 'r',
counters: StatementStatistics { _stats: [Object] },
updateStatistics: StatementStatistics { _stats: [Object] },
plan: false,
profile: false,
notifications: [],
server: ServerInfo { address: 'localhost:11001', version: 'Neo4j/3.4.7' },
resultConsumedAfter: Integer { low: 9, high: 0 },
resultAvailableAfter: Integer { low: 1, high: 0 } } }
1] record._fields[0].properties= { name: 'productType' }
2]record._fields[1] = [ Path {
start: Node { identity: [Object], labels: [Array], properties: [Object] },
end: Node { identity: [Object], labels: [Array], properties: [Object] },
segments: [ [Object] ],
length: 1 } ]
inside catch = Error: Can't set headers after they are sent.
Thanks. I resolved the issue.
The place and parameter i was passing in response was incorrect.
Correct code -
session
.run(` MATCH p=()-[r:Parameter]->() RETURN p ;`)
.then(function (result){
result.records.forEach(function(record){
console.log("record = ", record);
console.log("result = ", result)
console.log("1] record._fields[0].properties = ",record._fields[0].end.properties);
// res.send(record);
});
res.send(result);
})
.catch(function(err){
console.log("inside catch = " + err);
})
session.close();
}