How do I send multiple objects to .ejs file - node.js

I am trying to pass a query from MySQL to .ejs file, and send object at the same time.
In the following code, I am trying to send rows and { pageTitle: "Edit Agents" } to edit_agents page
Router.get("/", (req, res) => {
mysqlConnection.query("select * from agent", (err, rows, fields) => {
if (!err) {
res.render("edit_agents", rows);
res.render("edit_agents", { pageTitle: "Edit Agents" });
} else {
console.log("error");
}
});
});
Just to let you know, I am using NodeJs (express framework) with ejs views.

Router.get("/", (req, res) => {
mysqlConnection.query("select * from agent", (err, rows, fields) => {
if (!err) {
res.render("edit_agents", { data: rows,pageTitle: "Edit Agents" });
} else {
console.log("error");
}
});
});

Related

is there any way of accessing a variable inside one express route inside another different route?

i have this project where im populating a lists collection in database with todos in the show page of a 'board'.
This is the board showpage route
app.get('/boards/:id', (req, res) => {
Board.findById(req.params.id).populate('lists').exec(function(err, foundBoard) {
if (err) {
console.log(err.message);
} else {
List.findById(req.params.id).populate("todos").exec(function (err, foundlist) {
if (err) {
console.log(err);
} else {
console.log(foundlist);
res.render('show', { board: populatedboard ,list:foundlist});
}
});
}
});
});
and this is the route where the variable is i want to access.i want to access and use that variable in the board show route (const listid is the variable i want to use in the board show route)
app.post("/boards/:id/lists/:listid/todos",function(req,res){
Board.findById(req.params.id, function (err, foundBoard) {
if (err) {
console.log(err);
} else {
Todo.create(req.body.todo, function (err, newtodo) {
if (err) {
console.log(err);
} else {
console.log(newtodo);
List.findById(req.params.listid, function (err, foundlist) {
if (err) {
console.log(err)
} else {
**const listid**= req.params.listid;
foundBoard.todos.push(newtodo);
foundBoard.save();
res.redirect("/boards/" + foundBoard._id);
}
});
}
});
}
});
})

why does my express route work for "/" but not "/:id"?

I was troubleshooting why my route wasn't working and i came across this.
In my ./routes/jobs.js,
router.delete("/:id", (req, res) => {
Job.findByIdAndDelete(req.params.id, (err, job) => {
if (!err) {
res.json({ msg: "job deleted"});
} else {
console.log(err);
}
});
});
When i tested on postman, Delete - http://localhost:5000/dashboard/60b9405e1ea
Would return the id only 60b9405e1ea and not delete the db job.
I changed my route to "/" and tested it out. using http://localhost:5000/dashboard in postman.
router.delete("/", (req, res) => {
Job.findByIdAndDelete(req.params.id, (err, job) => {
if (!err) {
res.json({ msg: "job deleted"});
} else {
console.log(err);
}
});
It executed the delete request with {msg: "job deleted"}. (Obviously didnt delete db job since no id was given).
Keep in mind in my server.js im using,
app.use("/dashboard", require("./routes/jobs"));
Any help would be appreciated on why /:id is not being executed
As you are getting the id in the console, it's the problem with the query you make.
Try any of these,
Model.remove({ _id: req.body.id }, function(err) {
if (!err) {
message.type = 'notification!';
}
else {
message.type = 'error';
}
});
or
Model.findOneAndRemove({id: req.params.id}, function(err){
});
or a traditional approach:
Model.findById(id, function (err, doc) {
if (err) {
// handle error
}
doc.remove(callback); //Removes the document
})

Node/Express render multiple postgres queries on same html file

I have a query that returns results from my database, but I don't see how I can have it give me results from multiple queries.
router.get("/", function(req, res) {
pg.query("SELECT * from tic", (err, done) => {
if (err) {
console.log(err);
}
res.render("index", { tic: done.rows });
});
});
I was trying along the lines of this, but cant get it to work since he render statement is inside the query and I can get the render to see the results when I move it out of there
router.get("/", function(req, res) {
pg.query("SELECT * from tic", (err, tic) => {
if (err) {
console.log(err);
}
pg.query("SELECT * from tac", (err, tac) => {
if (err) {
console.log(err);
}
});
res.render("index", { tic: tic.rows }, { tac: tac.rows});
});
You just have to render after the second query executes. To do that you have to render in the callback of the second query.
router.get("/", function (req, res) {
pg.query("SELECT * from tic", (err, tic) => {
if (err) {
console.log(err);
}
pg.query("SELECT * from tac", (err, tac) => {
if (err) {
console.log(err);
}
res.render("index", { tic: tic.rows }, { tac: tac.rows });
});
});
});

Why my nodejs requests are slow?

Im new in nodejs, and Im trying to learn by creating an app that has a list of users, that I can add and remove those users. Im using angularjs in frontend to send request to nodejs and after that to mongodb. The problem is that, if I click a lot of times in the button "adduser" a lot of times, my app goes slow.
To interact to mongodb I use:
app.get('/users',function (req, res) {
mongoose.model('Usuario').find(function (err, list) {
res.send(list);
});
});
app.post('/addusuario', function (req,res) {
var usuario = new Usuario(req.body);
usuario.save(function (err) {
if (err) {
console.log(err);
} else {
console.log('Usuario salvo com sucesso');
}
}); });
app.delete('/delusuario/:id', function (req, res) {
var id = req.params.id;
mongoose.model('Usuario').findByIdAndRemove(id , function(err) {
if(err) {
console.log(err);
} else {
console.log('Usuario removido com sucesso!');
}
});
});
Im my angularapp:
app.controller('AppCtrl', function($scope, $http, Data) {
function reload() {
Data.get('users').then(function(data){
$scope.usuarios = data;
console.log(data);
});
};
$scope.addUsuario = function(usuario) {
Data.post('/addusuario', usuario);
reload();
};
$scope.deletarUsuario = function(id) {
Data.delete("/delusuario/"+id).then(function(result) {
});
reload();
};
reload();
});
I dont know why it is becaming slow after I click to add user more than 3 times..
What I see in your code that you are not sending an response back to the user, you should do something after insert or delete in the database. res.end();
You should rewrite your code in the following way:
app.get('/users',function (req, res) {
mongoose.model('Usuario').find(function (err, list) {
res.send(list);
});
});
app.post('/addusuario', function (req,res) {
var usuario = new Usuario(req.body);
usuario.save(function (err) {
if (err) {
console.log(err);
res.json({err: err});
} else {
res.json({ok: true});
console.log('Usuario salvo com sucesso');
}
}); });
app.delete('/delusuario/:id', function (req, res) {
var id = req.params.id;
mongoose.model('Usuario').findByIdAndRemove(id , function(err) {
if(err) {
console.log(err);
res.json({err: err});
} else {
res.json({ok: true});
console.log('Usuario removido com sucesso!');
}
});
});
You block the stack by not returning the response to the client. And this is most probably the cause of your slow request.

PUT and DELETE always route to GET in Node + Express

I'm a beginner in Node/Express. I tried to make an CRUD application but stuck at update and delete. I think my router code is problematic but I don't know why. The following code is in my controller, everything works but PUT and DELETE. It always route to GET. I tried to use next(); but it returns this error: Can't set headers after they are sent..
I can make the delete works by using GET /:company_id/delete but it's not a good and standardized solution. How can I get update and delete process worked?
'use strict';
var Companies = require('../../models/companies');
module.exports = function (router) {
// INDEX
// accessed at GET http://localhost:8000/companies
router.get('/', function (req, res) {
Companies.find(function(err, model) {
if (err) {
res.send(err);
}
else {
res.format({
json: function () {
res.json(model);
},
html: function () {
res.render('companies/index', model);
}
});
}
});
});
// CREATE VIEW
// accessed at GET http://localhost:8000/companies/create
router.get('/create', function (req, res) {
res.render('companies/create');
});
// CREATE DATA
// accessed at POST http://localhost:8000/companies
router.post('/', function (req, res) {
var name = req.body.name && req.body.name.trim();
var type = req.body.type && req.body.type.trim();
// VALIDATION
if (name === '') {
res.redirect('/companies/create');
return;
}
var model = new Companies({name: name, type: type});
model.save(function(err) {
if (err) {
res.send(err);
}
else {
res.redirect('/companies');
}
});
});
// READ
// accessed at GET http://localhost:8000/companies/:company_id
router.get('/:company_id', function(req, res) {
Companies.findById(req.params.company_id, function(err, model) {
if (err) {
res.send(err);
}
else {
res.render('companies/read', model);
}
});
});
// UPDATE VIEW
// accessed at GET http://localhost:8000/companies/:company_id/edit
router.get('/:company_id/edit', function(req, res) {
Companies.findById(req.params.company_id, function(err, model) {
if (err) {
res.send(err);
}
else {
res.render('companies/edit', model);
}
});
});
// UPDATE DATA
// accessed at PUT http://localhost:8000/companies/:company_id
router.put('/:company_id', function(req, res) {
Companies.findById(req.params.company_id, function(err, model) {
if (err) {
res.send(err);
}
else {
model.name = req.body.name;
model.type = req.body.type;
model.save(function(err) {
if (err) {
res.send(err);
}
else {
res.redirect('/companies');
}
});
}
});
});
// DELETE
// accessed at DELETE http://localhost:8000/companies/:company_id
router.delete('/:company_id', function (req, res) {
Companies.remove({ _id: req.params.company_id }, function(err) {
if (err) {
res.send(err);
}
else {
res.redirect('/companies');
}
});
});
};
HTML forms only support GET and POST. XMLHTTPRequest supports PUT and DELETE however, so you may have to go that route OR use something like method-override to allow HTML forms to submit using other HTTP verbs.

Resources