Neo4j NodeJS code doesn't display the entire nodes data - node.js

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();
}

Related

How to extract certain information from return type using apify API and Node.js

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.

firestore get data() not resolving the nested arrays

Running a nodejs code like
const snapshot = await db.collection('matches').where('series', '==', 'Series-2').get();
snapshot.forEach((doc) => {
console.log(doc.data());
});
Its returning me data like
{
inns: [
{
balls: [Array],
ballers: [Array],
bats: [Array],
isDeclared: false
},
{
bats: [Array],
balls: [Array],
isDeclared: false,
ballers: [Array]
},
{
bats: [Array],
ballers: [Array],
balls: [Array],
isDeclared: false
},
{
bats: [Array],
ballers: [Array],
isDeclared: false,
balls: [Array]
}
],
id: 'jgvjbvwF',
series: 'Series-2',
}
How can I get the full data i.e. instead of balls: [Array], it should be
balls: [
{ id: 1, runs: 0 },
{ id: 2, runs 1 },
...
]
You're getting full array of docs. So you want to extract all balls array from it.
This is example code for understand.
Suppose, if we're taking doc1 as our example.
So code will be :
let doc1 = snapshot[0].data().inns;
doc1.forEach((in)=> {
console.log(in.balls);
});
According to above code you can retrieve the all balls array from innings array

Saving array as output file of any format

I need help figuring out how to save the output from my array. I have tried appending the output to a csv, but this gives me an empty csv or a csv appended with the words [object] for each item in the array.
Here is a sample of the output in my array:
{
date: '2014-01-25',
firstBoxerRating: [Array],
firstBoxerWeight: 235.5,
judges: [Array],
links: [Object],
location: 'Golden Nugget Casino, Atlantic City',
metadata: 'Joseph Pasquale 75-77 | Tony Perez 78-74 | Barbara Perez 78-74\n' +
'<br>',
numberOfRounds: [Array],
outcome: 'win',
rating: 20,
referee: [Object],
result: [Array],
secondBoxer: [Object],
secondBoxerLast6: [Array],
secondBoxerRating: [Array],
secondBoxerRecord: [Object],
secondBoxerWeight: 236.5,
titles: []
},
{
date: '2014-05-16',
firstBoxerRating: [Array],
firstBoxerWeight: 240.75,
judges: [Array],
links: [Object],
location: '2300 Arena, Philadelphia',
metadata: 'Pierre Benoist 79-73 | Lynne Carter 78-74 | Eric Dali 79-73\n' +
'<br>',
numberOfRounds: [Array],
outcome: 'win',
rating: 20,
referee: [Object],
result: [Array],
secondBoxer: [Object],
secondBoxerLast6: [Array],
secondBoxerRating: [Array],
secondBoxerRecord: [Object],
secondBoxerWeight: 238,
titles: []
},
{
date: '2014-08-02',
firstBoxerRating: [Array],
firstBoxerWeight: 236.5,
judges: [Array],
links: [Object],
location: 'Revel Resort, Atlantic City',
metadata: ' time: 1:48\n' +
' | Lindsey Page\n' +
'<br>Williams down three times\n' +
'<br>',
numberOfRounds: [Array],
outcome: 'win',
rating: 20,
referee: [Object],
result: [Array],
secondBoxer: [Object],
secondBoxerLast6: [Array],
secondBoxerRating: [Array],
secondBoxerRecord: [Object],
secondBoxerWeight: 233,
titles: []
},
{
date: '2014-09-19',
firstBoxerRating: [Array],
firstBoxerWeight: 237,
judges: [Array],
links: [Object],
location: "Harrah's Philadelphia, Chester",
metadata: ' time: 1:34\n' +
' | <span>referee:</span> Benjy Esteves Jr<span> | </span>Bernard Bruni | Larry Hazzard Jr | Alan Rubenstein\n' +
'<br>',
numberOfRounds: [Array],
outcome: 'win',
rating: 20,
referee: [Object],
result: [Array],
secondBoxer: [Object],
secondBoxerLast6: [Array],
secondBoxerRating: [Array],
secondBoxerRecord: [Object],
secondBoxerWeight: 288,
titles: []
},
{
date: '2014-11-14',
firstBoxerRating: [Array],
firstBoxerWeight: 244,
judges: [Array],
links: [Object],
location: "Harrah's Philadelphia, Chester",
metadata: ' time: 2:28\n' +
' | <span>referee:</span> Benjy Esteves Jr<span> | </span>Eric Dali | Larry Hazzard Jr | Mike Somma\n' +
'<br>',
numberOfRounds: [Array],
outcome: 'win',
rating: 40,
referee: [Object],
result: [Array],
secondBoxer: [Object],
secondBoxerLast6: [Array],
secondBoxerRating: [Array],
secondBoxerRecord: [Object],
secondBoxerWeight: 209,
titles: []
},
I am assuming that this output is a JSON object.
This is the code I used to produce this output:
async function writeData() {
const csv = require('csv-parser')
const results = [];
fs.createReadStream('C:\\Users\\User\\Documents\\testingclean.csv')
.pipe(csv())
.on('data',(data)=> results.push(data))
.on('end', async () => {
const cookieJar = await getCookieJar();
const promises = [];
results.forEach((data) => {
promises.push(boxrec.getPersonById(cookieJar,data.id));
})
const fighters = await Promise.all(promises); // Fighters is an array
fighters.forEach((fighter) => {
console.log(fighter.output);
})
});
};
try {
writeData();
} catch (error) {
console.log("Error in writeData: " + error);
}
Something like this should work.
fighters.forEach((fighter) => {
let data = '';
for (const key in fighter.output) {
if (Array.isArray(fighter.output[key])) {
data += JSON.stringify(fighter.output[key]) + ',';
} else if (typeof fighter.output[key] === 'object') {
data += JSON.stringify(fighter.output[key]) + ',';
} else {
data += fighter.output[key] + ',';
}
}
data = data.replace(/(^,)|(,$)/g, ""); // Remove trailing comma
data += '\n'; // Add new line
fs.appendFile('data.csv', data, (err) => {
if (err) throw err;
});
});
Didn't test the code. Also, the data.csv file might take some time to create depending on data size. The forEach look will finish even before nodejs is done with writing file. So, the program might exit but in the background writing might go on until its done. You have to maintain the async execution part. How to handle it is not in scope of this question.

error when hitting GET route but data shows up

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!

Getting at all fields in the response to a monk findById call. nodejs/express/monk

Just cannot get my head around this after 10 hours of trying:
if I
users.findById(req.body.user_id,function(e,doc){});
and console.log the doc returned, all looks good:
{ _id: 54dcad6de4b01007caacb0cd,
username: 'realizertest',
password: '******************************',
first_name: 'Realizer',
second_name: 'Test',
display_name: 'Realizer Test',
email: 'system#realizerlabs.com' }
However, when trying to access the included fields, e.g. by:
user = users.findById(req.body.user_id,function(e,doc){});
var user_email = user.email;
I just get undefined. The user object looks like this:
{ col:
{ manager:
{ driver: [Object],
helper: [Object],
collections: [Object],
options: [Object],
_events: {} },
driver:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_connect_args: [Object] },
helper: { toObjectID: [Function], id: [Ob
name: 'users',
col:
{ _construct_args: [],
_native: [Object],
_emitter: [Object],
_state: 2,
_skin_db: [Object],
_collection_args: [Object],
id: [Object],
emitter: [Object] },
options: {} },
type: 'findOne',
opts: { fields: {}, safe: true },
domain: null,
_events:
{ error: [ [Function], [Function] ],
success: [ [Function], [Function] ] },
_maxListeners: 10,
emitted: {},
ended: false,
success: [Function],
error: [Function],
complete: [Function],
resolve: [Function],
fulfill: [Function],
reject: [Function],
query: { _id: 54dcad6de4b01007caacb0cd } }
I've also tried user.query.email but get the same result.
The findById obviously doesn't return a JSON object that I can use in this way.
How can I get at these fields?
It's an async call, so you need to use the callback, you can't assign that function to a variable:
users.findById(req.body.user_id,function(e,doc){
var user = doc;
console.log(user); //should see the object now, and access the props
});

Resources