Node.js shows [object Object] instead of result.row - node.js

I'm using postgresql version 11 and have a user with id=3 with a post field(text type). when I want to show the post from database it shows [object Object] instead of the post with id=3
const express = require('express');
const app = express();
const { Pool, Client } = require('pg')
const connectionString = 'postgresql://postgres:1111#localhost:5432/netSecure'
const pool = new Pool({
connectionString: connectionString,
})
app.get('/h', (req, res) => {
pool.query('SELECT post from users where id=3', (err, result) => {
if(err) return console.log('error in query',err);
console.log(result.rows);
res.render('posts.pug', {
post: result.rows
});
res.end();
});
app.listen(3000, () => console.log('http://localhost:3000'))
pug file with #{post}:
body
form(action='/posts',method='post')
label(for='exampleFormControlTextarea1') Enter Your Post
textarea(autofocus='', placeholder='Post your message here...')#exampleFormControlTextarea1.form-control(rows='3')
button(type="button").send Send
form(action='/logout',method='post')
button.logout Logout
p #{post}
Where did I make mistake?

[object Object] is the default toString representation of an object in javascript.
It seems that you only want to retrieve one post with id = 3. So first you need to extract one result because postgresql will give you an array of result no matter what.
And then, you need to process the JSON object so that it is not shown as [object Object]. For quick solution, you can use JSON.stringify()
So here is the snippet of your code
app.get('/h', (req, res) => {
pool.query('SELECT post from users where id=3', (err, result) => {
if(err) return console.log('error in query',err);
// need to check if post exists
let post = (result.rows.length > 0) ? result.rows[0] : null;
let postInString = JSON.stringify(post);
console.log(postInString);
res.render('posts.pug', {
post: postInString,
});
res.end();
});

The problem seems to be that you are trying to console.log something that is not in string format; this is why you are seeing [Object object].
To log what you actually want, consider first turning the object into a string with JSON.stringify(result.rows).

Related

How to take and output documents from a MongoDB database with NodeJS?

I've been working on one of my first API projects with NodeJS, Express and MongoDB. I can save new documents into the database with collection.insertOne(newDocument) method but I can not take existing documents and output them using collection.find({}).
Can you please help me:')
export const visualizeUser = (req, res) => {
console.log("you are searching the user with username " + req.body.username);
users.find({username: 'yavuz'}, (err, data) => {
if(err)
console.log(err);
else
console.log(data);
});
}
thats the code I have written.
MongoInvalidArgumentError: Argument "options" must not be function
and that is the error I am getting.
Your help is really appreciated.
Like error message is saying, you cannot pass function as options argument.
Look here: docs
Your code should look like this:
const visualizeUser = async (req, res) => {
try{
console.log("you are searching the user with username " +
req.body.username);
let data = await users.find({username: 'yavuz'});
console.log(data)
} catch(e) {
console.log(e)
}
}

How to send a NODE.JS post request from an Angular Project?

I have a NODE.JS api using expressjs that connects to an SQL Server, and I want to use it in an angular project. I make use two files, a route file and a controllers file. My route file is as follows:
module.exports = (app) => {
const UsrContrllr = require('../Controllers/users.controllers');
//1. GET ALL USERS
app.get('/api/users', UsrContrllr.func1);
//2. POST NEW USER
app.post('/api/user/new', UsrContrllr.func2);
};
And my controllers file is given below:
const mssql = require('mssql');
exports.func1 = (req, res) =>
{
// Validate request
console.log(`Fetching RESPONSE`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `SELECT * FROM USERS`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() === '') {
res.send('Oops!!! Required data not found...');
}
else {
// send records as a response
res.send(recordset);
}
};
});
};
exports.func2 = (req, res) =>
{
// Validate request
console.log(`INSERTING RECORD ${req}`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `INSERT INTO GDUSERS (USERCODE, PASSWORD, LANGUAGE, USERCLASS, FIRSTNAME, LASTNAME, CONTACTNO) VALUES ('${req.body.usercode}', '${req.body.password}', 'EN', '0', '${req.body.firstname}', '${req.body.lastname}', '${req.body.contactno}');`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() == '') {
res.send('Oops!!! Required data not found...');
}
else {
// Send records as response
res.send(recordset);
}
};
});
};
The GET request works well, but when I try to run the POST request directly from the angular application, I get an error stating
Cannot GET URL/api/user/new
The angular code in my angular project is:
signup() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(this.user); //User details come from a form
this.http.post(“URL", this.user, options)
.subscribe(
(err) => {
if(err) console.log(err);
console.log("Success");
});
}
I’m not sure whether the angular code I’m using, is right or not, and I don’t know where I’m going wrong. How does one exactly send a http POST request from an Angular project?
this i the way i handled my user signup with http.post calls. my approach is slightly different when signing up user because i am using a promise instead of observable (which i normally use for my servicecalls). but i will show you both ways.
createUser(user: User): Promise < string > {
const promise = new Promise < string > ((resolve, reject) => {
const userForPost = this.createUserForPost(user);
this.http.post(environment.backendUrl + '/api/user/signup', userForPost, this.config).toPromise < HttpConfig > ()
.then(createdUser => {
}).catch(error => {
console.log(error);
});
});
return promise;
}
here another example with an observable
createForumPost(forumPost: ForumPost) {
this.http.post < { message: string, forumPostId: string } > (environment.backendUrl + '/api/forumPosts', forumPost).subscribe((responseData) => {
const id = responseData.forumPostId;
forumPost.id = id;
});
}
i defined my URL somewhere else and then just use the environment.backedUrl + 'path' to define my path (the same as the path in your backend controller)
this is one of my first answers here on SO. i am sry if it is a bit messy
i hope i was able to help with my examples :)

CSV File downloads from Node Express server

I have an API backend with Node and Express. I am trying to take some filtered data from the frontend and create a CSV file and download it for the user. I have been using json2csv. I am able to create the data file correctly and when I use that file in my express route I download a file that just says undefined. At first, I thought it was an asynchronous issue, but after using a setTimeout as a test to see if that was an issue I still get the undefined data file. Console logging the "csvData" shows the correct data.
Express route to download the file.
app.post('/api/downloads/filtered', (req, res) => {
let fields = [];
fields = Object.keys(req.body[0])
const filteredData = req.body;
const json2csvParser = new json2csv({fields: fields});
const csvData = json2csvParser.parse(filteredData);
console.log(csvData)
fs.writeFile('./report.csv', csvData, (err) => {
if (err) {
console.log(err);
}
else {
console.log('created report.csv');
res.download('./report.csv');
}
})
})
I'm using Vue on the frontend, I get the file when clicking a button not sure if that is something I should include.
I ended up figuring out my issue. I found that downloading in a post request didn't seem to be possible. I needed a get request. Since the data for the file came in the request body I ended up keeping the post request to create the file and creating a separate get request to download the file this seemed to work fine but didn't find it documented anywhere so I wasn't sure if a better way exists.
app.post('/api/downloads/filtered', (req, res) => {
console.log(req.body)
let fields = [];
fields = Object.keys(req.body[0])
const filteredData = req.body;
const json2csvParser = new json2csv({fields: fields});
const csvData = json2csvParser.parse(filteredData);
console.log(csvData)
fs.writeFile('./report.csv', csvData, (err) => {
if (err) {
console.log(err);
}
else {
console.log('created report.csv');
}
})
})
app.get('/api/downloads/filtered', (req, res) => {
setTimeout(() => {res.download('./report.csv')}, 1000)
})

Can't bind params in nodejs

I want to bind params in node js and this is my code but shows some erros,
app.get("/single/:id", async (req, res) => {
let id = req.params.id;
console.log(id);
try{
const singleMovie = await Movies.findById(id)
res.render("single", {
singleMovie: singleMovie
});
}catch(err){
console.error(err.message);
}
});
shows me this warning,
Cast to ObjectId failed for value "undefined" at path "_id" for model
"Movies" and id is undifined
any way to fix this?
In your code res.render("single", { should be res.json("single", {
Try the code below... sending the response in json just to test it....
if you get the same error you are getting, then there is a problem somewhere in your code. Because The block of code you posted looks fine!
app.get("/single/:id", async (req, res) => {
let id = req.params.id;
console.log(id);
try{
const singleMovie = await Movies.findById(id)
res.json({
singleMovie: singleMovie
});
}catch(err){
console.error(err.message);
}
});
Also make sure you are using nodejs -v 8+ and mongoose -v 5+

How To Bind Node-js DB Query to Web Form

I'm using node and postgres, I'm new to writing async function, what I'm trying to do is a very simple query that will do a total count of records in the database, add one to it and return the result. The result will be visible before the DOM is generated. I don't know how to do this, since async function doesn't return value to callers (also probably I still have the synchronous mindset). Here's the function:
function generateRTA(callback){
var current_year = new Date().getFullYear();
const qry = `SELECT COUNT(date_part('year', updated_on))
FROM recruitment_process
WHERE date_part('year', updated_on) = $1;`
const value = [current_year]
pool.query(qry, value, (err, res) => {
if (err) {
console.log(err.stack)
} else {
var count = parseInt(res.rows[0].count) + 1
var rta_no = String(current_year) + '-' + count
callback(null, rta_no)
}
})
}
For the front-end I'm using pug with simple HTML form.
const rta_no = generateRTA(function (err, res){
if(err){
console.log(err)
}
else{
console.log(res)
}
})
app.get('/new_application', function(req, res){
res.render('new_application', {rta_number: rta_no})
});
I can see the rta_no in console.log but how do I pass it back to the DOM when the value is ready?
Based on the ajax call async response, it will update the div id "div1" when it gets the response from the Node js .
app.js
app.get("/webform", (req, res) => {
res.render("webform", {
title: "Render Web Form"
});
});
app.get("/new_application", (req, res) => {
// Connect to database.
var connection = getMySQLConnection();
connection.connect();
// Do the query to get data.
connection.query('SELECT count(1) as cnt FROM test ', function(err, rows, fields) {
var person;
if (err) {
res.status(500).json({"status_code": 500,"status_message": "internal server error"});
} else {
// Check if the result is found or not
if(rows.length==1) {
res.status(200).json({"count": rows[0].cnt});
} else {
// render not found page
res.status(404).json({"status_code":404, "status_message": "Not found"});
}
}
});
// Close connection
connection.end();
});
webform.pug - Via asynchronous call
html
head
script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js')
script.
$(document).ready(function(){
$.ajax({url: "/new_application", success: function(result){
$("#div1").html(result.count);
}});
});
body
div
Total count goes here :
#div1
value loading ...
That seems okay, I'm just not sure of this:
The result will be visible before the DOM is generated
This constraint defeats the purpose of async, as your DOM should wait for the returned value to be there. Instead of waiting for it you could just render the page and once the function returns and runs your callback update the value.
Also, perhaps it's worth having a look into promises

Resources