Saving array as output file of any format - node.js

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.

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

Problems with localbitcoins api pagination on nodejs

I'm developing with the LocalBitcoins API using nodejs. Heres the code
const adsList = async (action, options = {}, page) => {
let prefix = action + '-'
let countryCode = (options.countryCode) ? options.countryCode : false
let countryName = (options.countryName) ? options.countryName : false
let paymentMethod = (options.paymentMethod) ? options.paymentMethod : false
let currency = (options.currency) ? options.currency : false
let basePath = prefix + 'bitcoins-online'
let suffix = (page > 1) ? `.json?page=2` : '.json'
let path
if (currency) {
path = (paymentMethod) ? `${basePath}/${currency}/${paymentMethod}/${suffix}` : `${basePath}/${currency}/${suffix}`
} else if (countryCode && countryName) {
path = (paymentMethod) ? `${basePath}/${countryCode}/${countryName}/${paymentMethod}/${suffix}` : `${basePath}/${countryCode}/${countryName}/${suffix}`
} else if (!currency && !countryCode && !countryName) {
path = (paymentMethod) ? `${basePath}/${paymentMethod}/${suffix}` : `${basePath}/${suffix}`
}
let response = await get(path, true)
return response
}
Now when I make a call with no page given, everything works fine.
adsList('sell', {
countryCode: 'co',
countryName: 'colombia'
}).then(response => {
console.log(response)
})
The output:
{
pagination: {
next: 'https://localbitcoins.com/sell-bitcoins-online/co/colombia/.json?page=2'
},
data: {
ad_list: [
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object], [Object], [Object],
[Object], [Object]
],
ad_count: 50
}
}
Ah, but when I add a page:
adsList('sell', {
countryCode: 'co',
countryName: 'colombia'
}, 2).then(response => {
console.log(response)
})
This is the output:
{
error: {
message: 'HMAC authentication key and signature was given, but they are invalid.',
error_code: 41
}
}
I have been working on this for hours but and searching info but there is nothing, so if you have any solution I will be grateful.

Neo4j NodeJS code doesn't display the entire nodes data

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

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