Error in res.render, function not defined - javascript

I have developed an application using express js. I am trying to fetch data from my mongo collection, below is the javascript file and on fetching the data i am passing the data to a jade file through res.render function. One point to note is that i have several functions like the one below and all are synchronous. Still my console says "TypeError: undefined is not a function"
It is showing error on res.render line.
Any help is deeply appreciated. If someone needs more info about the question, please let me know.
exports.getData_app = function(req,res){
var nine = function(callback){
wpt_results.find({$and: [{"Environment":"app"},{"Module":"paid"},{browser_name:'Internet Explorer'}]},{},function(e,docs){
console.log('here is the doc fetched from the collection app');
// console.log(docs);
len = docs.length;
console.log('here is the length of the docs fetched in app');
console.log(len);
console.log("we are in the new one app javascript file");
console.log("here is the much awaited result"+req.params.id);
for(i=0;i<docs.length;i++){
dates_apppaid_ie.push(docs[i].Date);
ttfbs_apppaid_ie.push(docs[i].TTFB);
lt_apppaid_ie.push(docs[i].loadTime);
url.push(docs[i].Url);
}
for(i=0;i<len;i+=2){
pre_final_str_apppaid_ie.push(dates_apppaid_ie[i]+","+ttfbs_apppaid_ie[i]+","+ttfbs_apppaid_ie[i+1]+","+lt_apppaid_ie[i]+","+lt_apppaid_ie[i+1]+"\\n");
}
console.log(pre_final_str_apppaid_ie);
console.log(pre_final_str_app.length);
for(i=0;i<pre_final_str_apppaid_ie.length;i+=2){
final_str_apppaid_ie += pre_final_str_apppaid_ie[i].concat(pre_final_str_apppaid_ie[i+1]);
}
console.log('app ---->>>>>'+final_str_apppaid_ie);
res.render('index1.jade',{final_str_appreporting: final_str_appreporting,final_str_apppaid: final_str_apppaid, final_str_app: final_str_app, final_str_app_firefox:final_str_app_firefox,final_str_appreporting_firefox:final_str_appreporting_firefox,final_str_apppaid_firefox:final_str_apppaid_firefox,final_str_app_ie:final_str_app_ie,final_str_appreporting_ie:final_str_appreporting_ie,final_str_apppaid_ie:final_str_apppaid_ie});
});
callback(null,nine);
}

Got it. I was getting this error because i had defined a string with the name "res". On changing it to something else, res.render is working fine.

Related

Capture messages in from python-shell in an array

I am new to Javascript but am attempting to build an Electron app as a gui to a python script.
I am using python-shell to call my Python script and can successfully do this and printing the output in the console. However I would like to capture multiple Python print statements in a Javascript array.
Following the python-shell docs I can access each Python print statement via the message event.
var res = [];
var ligation = PythonShell.run("ligation.py", options, function (err, results) {
if (err) throw err;
// console.log('results: %j', results);
});
ligation.on('message', function(message) {
// console.log(message)
res.push(message)
})
console.log(res)
However when I try to assign the ouput of these events to an array it works but I cannot access the values as the console looks like this:
where the 8 numbers are my output. When I try to access a single value (e.g. console.log(res[0])) I get it reported that it is undefined.
I gather that the little blue i means that the values are just evaluated and figure this may have something to do with it but I do not know what.
I figure there must be something straightforward I am missing. Any help is appreciated.

firebase admin with node.js: update in nested JSON tree

I use the below code on my Node.js admin server to retrieve data from my JSON tree, which works fine and prints the content of all snapshot2's to the console.
ref.once("value", function(snapshot0) {
snapshot0.forEach( function(snapshot1) {
snapshot1.child("Food").forEach( function(snapshot2) {
console.log(snapshot2.val());
});
});
});
However, how can I edit the data held at snapshot2?
If I try to call e.g.
snapshot2.update({250:42})
then it gives me the following error:
TypeError: snapshot2.update is not a function
I am really confused and think this must be a problem many people have?
You cannot update a snapshot. but you can update a reference, and you can get reference from snapshot by doing
snapshot.ref
, then you can do this to update
snapshot.ref.update({250:42})

NodeJS FS not returning data from multiple files

var market = fs.readdirSync(__dirname+"/c/")
console.log(market)
for(i in market){
console.log(market[i]) // <----- shows contents of folder
fs.readFile(market[i],'utf-8',function(err,data){
console.log(data) // <---- retruns undefined
})
}
So I thought this would be alot easier, but clearly i'm messing up somewhere.
as you can see, console.log(market[i])shows the contents of the folder, but if i try to read them, i just get returned "undefined", anyone have a clue on why this is happening? I'm trying to read the data of each file, basically later im going to store it, and send it, but thats not a problem right now, the bigger concern is it not even reading the data from the files :U.
You need to provide a full path to the readFile, while readdirSync returns you only file names, so the correct code would be:
var market = fs.readdirSync(__dirname+"/c/")
console.log(market)
for(i in market){
console.log(market[i]) // <----- shows contents of folder
fs.readFile(__dirname + "/c/" + market[i],'utf-8',function(err,data) {
console.log(data) // <---- retruns undefined
})
}

Firebase's .once() Query Method Doesn't Stop Listening After Being Called [duplicate]

This question already has answers here:
node process doesn't exit after firebase once
(4 answers)
Closed 7 years ago.
I'm a totally new Firebase user, trying to build a simple application -- and I'm running into an odd issue that I haven't been able to find a solution to.
Here's what I'm doing.
I've got a simple Firebase database of users, that looks something like this:
{
"users": {
"randomlyAssignedId": {
"phoneNumber": "+18882223333"
}
}
}
The idea is that I'll have one user object (and each user object only contains a phoneNumber field) for each user using my service.
I've got this stored in Firebase and working already.
Now, here's where things are getting tricky. I want to write a query which returns a user by their phoneNumber. So, after reading the Firebase docs, here's what I came up with:
var Firebase = require('firebase');
var users = new Firebase('https://demo.firebaseio.com/users');
users.orderByChild('phoneNumber').equalTo('+18882223333').limitToFirst(1).once('value', function(snapshot) {
console.log('API call succeeded:', snapshot.val());
}, function(err) {
console.log('Firebase returned an error:' err);
});
When I run this code sample, the user object is logged to the console successfully (it found the match, yey!), however -- the callback never finishes.
According to the Firebase docs for .once(): https://www.firebase.com/docs/web/api/query/once.html the success (or error callback) should fire exactly ONE time.
This doesn't appear to be happening :(
Could anyone tell me if this is the desired behavior, or if I'm doing something wrong?
Thanks! <3
I think what you're expecting is just a little off.
You have 2 functions in your .once() call :
.once("value",function(snapshot){
....
},function(err){
console.log('Did not find a user in the database:');
console.log(err);
})
However, the 2nd function where you are looking for a possible err value is not going to be utilized if the data is not found. The 2nd function is there to catch a lack of authorization/permission. I think you are looking for something like this:
.once("value",function(snapshot){
if(snapshot.val()){
console.log('Found existing user by phoneNumber in database:');
console.log(snapshot.val());
}else{
console.log('Did not find a user in the database:');
console.log(err);
}
},function(err){
console.log('Not authorized');
console.log(err)
})
If your data (user's phone number) is not found in the database then the result of the snapshot.val() will be null. The 2nd callback function will only contain an err value if you have auth rules set on your firebase and they are not met when making this request.
You can read more here:
https://www.firebase.com/docs/web/api/query/once.html

Node.js connecting to a mongodb

I have been following this tutorial to try and get mongodb node.js, express, and jade to work together, but I can not for the life of me get the program to access any information from the database.
here is the code in app.js that is supposed to access the database.
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
....a few lines down....
app.use(function(req,res,next){
req.db = db;
next();
});
here is the code handling the routes:
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
And here is the code in userlist.jade: it is designed to purely figure out what the contents of userlist are. It is supposed to contain the information in the database (which has 3 entries with 2 pieces of data for each). I have other jade code from an example online that runs and is essentially just a 'Hello World' program.
doctype html
html(lang="en")
head
title= pageTitle
body
#{userlist}
the page outputs to this:
<[object Object],[object Object],[object Object]>
This explains why I was getting errors looping through the data, but what I need help with is getting the program to actually get the proper information from the database.
Extra information:
I can access the database through command prompt and view the data I put it.
I am using Windows 8.1
Update: code that makes it work!
index.js (route handler):
/* GET Userlist page. */
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
userlist.jade
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
I'm not sure exactly why this is working now because I did a lot of testing to make sure I was sending the right data over which include copying and pasting code from the tutorial, but it works now!
Edit: I got closer to the solution by confirming that it is in fact pulling data from the server, just tested it and verified with the tutorial the code I should be using and it is now functioning properly. Added proper code.
I believe you are getting this output because docs in the callback is an array. Can you loop through docs and simply print individual documents to the console? This will verify that the data access part is working, and you can figure out HTML output afterwards.

Categories

Resources