This is my first project with nodejs, and probably I am asking something trivial.
I hava a table to display list of items, that can be filtered in between two date.
The table has a link to edit and a form button to delete.
When I click to edit a line, I move to the editing page, I perform my actions and when I go back to the filtered page this is reloaded.
I follow answer 2 of this question, how to force page refresh on browser back click?
My problem is that I cannot achieve the same result with the delete form.
I tried res.redirect('back'); and res.redirect(req.get('referer'));
Can I be pointed to the right direction ?
Thanks Alb
app.search('/search', function(req, res) {
var sdate = req.body.sdate
var edate = req.body.edate
var sdate_full = req.body.sdate+' 00:00:00'
var edate_full = req.body.edate+' 24:59:59'
console.log("post received: %s %s", sdate, edate);
console.log("post received: %s %s", sdate_full, edate_full);
req.getConnection(function(error, conn) {
conn.query("SELECT * FROM item WHERE item_INSERT_DATE >= ? AND item_INSERT_DATE <= ?", [sdate_full, edate_full], function(err, rows) {
if (err) {
req.flash('error', err)
res.render('user/list', {
moment: moment,
title: 'Items',
data: ''
})
} else {
res.render('user/list', {
moment: moment,
title: 'Items',
data: rows
})
}
})
})
})
app.delete('/delete/(:id)', function(req, res, next) {
var user = { item_ID: req.params.id }
req.getConnection(function(error, conn) {
conn.query('DELETE FROM table WHERE item_ID = ' + req.params.id, user, function(err, result) {
if (err) {
req.flash('error', err)
res.redirect('/')
} else {
req.flash('success', 'Item deleted ! id = ' + req.params.id)
res.redirect(??????)
}
})
})
})
The form I start from is '/search', which filter my table list. The problem is that I can only redirect to '/' (which gives me the entire list), but not the search page updated with the line deleted. This is the last tiny bit to end this little job.
the simplest thing you could do is, when you click in the delete button in the frontend, call
const desiredTimeInMilliSeconds = 100;
setTimeout(function() {
window.location = window.location;
}, desiredTimeInMilliSeconds)
Related
Even after deleting all rows in the table continues. It continues adding from the last inserted id.
I used this to create my table
app.get('/createuserstable', (req, res) => {
let sql = 'CREATE TABLE Users(id int AUTO_INCREMENT, name VARCHAR(255), username VARCHAR(255), email VARCHAR(255), PRIMARY KEY (id))';
db.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
res.send('Users table created....');
});
});
adding users with a signup route and it keeps incrementing in steps of 10
app.post('/signup', (req, res) => {
let user = { name: req.body.name, username: req.body.username, email: req.body.email };
db.query('INSERT INTO users SET?', user, (error, result) => {
if (error) throw error;
res.status(201).send(`User added with ID: ${result.insertId}`);
});
});
this is the code that is used the 10 rows of json data
app.get('/populate', (req, res) => {
request({
url: "http://jsonplaceholder.typicode.com/users",
json: true
}, (err, resp, body) => {
//res.send(typeof body);
for (var i = 0; i < body.length; i++) {
let post = { id: body[i].id, name: body[i].name, username: body[i].username, email: body[i].email };
let sql = 'INSERT INTO users SET?';
let query = db.query(sql, post, (err, result) => {
if (err) throw err;
console.log(result);
});
};
res.send('users data added....')
});
});
You've increased the auto_increment_increment system variable from the default value of 1 to 10. Its scope is Global, Session so you can either set it for current session or change it for the entire server (the first option used to be restricted prior to MySQL/8.0.18).
If you don't need it at all I suggest you just find the directive in the settings file and comment it out.
That's normal behavior of MySQL and often intended, so that IDs are never re-used, even for deleted records.
If you really need to reset auto-increment counter, you could either:
emptying whole table at once with TRUNCATE TABLE users
drop and re-create the table with DROP TABLE users / CREATE TABLE users ...
ALTER TABLE users AUTO_INCREMENT = 1;
See also https://www.mysqltutorial.org/mysql-reset-auto-increment/
I have a company that have a job opening, and other users that want to work there have to make orders to that job position. Overy order has an id of the user that make´s it. I want to also show the name of that user when the company wants to see all the orders for a job.
So, what I was doing was just get all the orders with Order.getOrder, and then get name and email from user for every order and add it to what I am going to return.
The error I´m getting is TypeError: Cannot read property 'then' of undefined in the last then
router.get("/orders", verifyToken, (req, res) => {
Order.getOrders(req.userId, (err, rows) => {
for (x in rows) {
console.log(rows[x].id);
User.forge({id: rows[x].id}).fetch({columns:['email','name']}).then(user => {
rows[x].nameTester = user.get('name');
rows[x].emailTester = user.get('email');
});
}
}).then(function(err, rows) {
res.json({orders: rows});
});
});
And this
Order.getOrders = (userData, callback)=>{
if (connection) {
const query = ...sql query...
connection.query(query, [userData], (err, result, fields) => {
if (err) {
throw err;
} else {
callback(null, result);
}
});
}
};
I'm using SailsJS as an API with Waterline connected to a MongoDB. I'm trying to put together an endpoint to edit existing DB entries but can't seem to get it to work and I'm hitting a wall as to why.
My route:
'post /edit/safety/:id': {
controller: 'SafetyController',
action: 'editSafety'
},
My controller function:
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOneById(id).then((err, safety) => {
if (err) {
res.send(500, err);
return;
}
if (!safety) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
safety.save((err, updatedSafety) => {
if (err) {
re.send(500, err);
return;
}
res.send(200, updatedSafety);
});
});
},
Any push in the right direction would be greatly appreciated.
I don't recognize the Safety.findOneById method - is this something you have custom built? If not, then it is likely your problem.
Try swapping it for either:
Safety.findOne(id)
or
Safety.findOne({id: id})
Note that the returned object will be a model instance if the record exists, and undefined otherwise. If you decide to go with Safety.find instead then the returned value will be an array containing all models matching the query.
Looks like the main issue was transposing the response and err objects. It was successfully completing the query, but loading it into the err object which gets caught and a 500 error is thrown. So I changed that and simplified in a few other places.
editSafety: function editSafety(req, res) {
var id = req.params.id;
Safety.findOne(id).then((response, err) => {
var safety = response;
if (err) {
res.send(500, err);
return;
}
if (!response) {
res.send(404, err);
return;
}
safety.title = req.body.title;
safety.description = req.body.description;
safety.status = req.body.status;
Safety.update({
id: id
}, safety)
.then((result) => {
res.json(200, 'Ok!');
})
.catch((err) => {
sails.log.error('SafetyController.editSafety', err);
})
});
},
I am stuck trying to update MongoDB with added req.body.whatever data.
When I get the req.body data to my route, I can see it, change it and update to the database just fine, but when I add say, a new element into the req.body like so:
req.body.newData = "this is new";
In the route, it will not populate into MongoDB with the rest of the existing (changeable) req.body data that already exists in the DB document.
I can in code change an existing req.body.(KeyElement), and updates fine to the DB. Once I try to add an element to req.body, the new one just doesn't get updated. Tried all different update, modify, replaceOne etc and can get an editable result, but still no new elements being added to the database. I even tried the
Model.update(query, {$set: req.body}); etc
and this seems to update as well but nothing new gets added.
Here is the route I'm working with...
router.post('/set-repair-info', ensureAuthenticatedAdmin, function(req, res) {
console.log('set-repair-info : ');
var ObjectId = require('mongodb').ObjectID;
var b = req.body;
console.log('body: ');
console.log(req.body);
var repairToUpdate = req.body.jid;
// console.log(repairToUpdate);
// console.log('req.body[uid]');
// console.log(req.body.jid);
// console.log('userid::: ' + req.body.userid);
// console.log('backuped : ' + req.body.backedup);
// console.log(req.body.username);
//buggy without this;
if (req.body.backedup=='false'){
req.body.backedup == '';
}
//CHECKS AND RESPONSES:
//by Edit
//PARTS ORDERED
if(req.body.repairstatus == 'Parts Ordered'){
req.body.partsordered = 'true'; //THIS WILL NOT GO INTO DB!
} else{
req.body.partsordered = null;
}
req.body.testthisout = "THIS IS A TEST"; //THIS WILL NOT GO INTO DB!
console.log("parts: " + req.body.partsordered);
// Job.replaceOne({ _id: ObjectId(req.body.jid)}, req.body , {upsert: true}, function (err, result) {
// (err === null) ? {msg: 'something happened... err edit user'} : {msg: err}
// });
console.log('body updated: ');
console.log(req.body);
req.body.repairstatus = "Waiting For Something Else"; // UPDATES FINE
Job.update({ _id: ObjectId(req.body.jid)}, { $set: req.body }, function (err, result) {
(err === null) ? {msg: 'something happened... err edit user'} : {msg: err}
});
req.flash('success_msg','Repair has successfully been edited and saved to the database.');
res.render('edit-repair', { job: {'data': req.body} });
});
Double check your Models Schema and make sure variable is setup there.
Check your routes that create an instance of the Schema, make sure value is in there. And .save() or update through mongoose method.
SAVE the file.
I'm still trying to get into node.js and probably getting some things not quite right. What I'm looking foward to accomplish is to query first a hmap containing a list of rooms. This list is going to be iterated trough to get for each room further details like room name etc.
Here's what the query should return:
redis 127.0.0.1:6379> lrange rooms 0 -1
1) "room:5000"
and
redis 127.0.0.1:6379> hgetall room:5000
1) "name"
2) "room1"
3) "admin"
4) "user:1001"
5) "public"
6) "true"
here's my function within the routes.index
exports.index = function(req, res){
var render_rooms = new Array();
req.app.settings.redis.lrange('rooms',0,-1, function(error, rooms) {
if (error) {
console.log('Error: '+ error);
}
else {
rooms.forEach(function(room){
console.log("room: " + room);
req.app.settings.redis.hgetall(room, function(error, roomdetails){
if (error) {
console.log('Error: '+ error);
}
else {
console.log("roomdetails: " + roomdetails.public);
if(roomdetails.public == "true"){
render_rooms.push(roomdetails.name);
}
}
});
});
// console.log('Name: ' + result);
// res.render('account', { title: 'account title', user: req.user.username, votes: result });
}
});
console.log("length: " + render_rooms.length);
res.render('index', { title: 'Index', username: req.user.username, rooms: render_rooms });
};
I'm not sure if I'm using node_redis properly to achieve this. Further I came up with the idea to store all room details in an array which I'm looking forward to send to the view. Apparently the list always display no elements as I guess is called before the list is filled as I'm missing some essential callback functionality. Howeever I'm not able to fiddle it in. Can someone explain me in some more detail how it "should" work?
Your basic problem is that you need to wait to render the render_rooms array until all the asynchronous processing has completed. The way it is written now, res.render is being called before any of the async Redis queries have completed.
Something like this:
exports.index = function(req, res){
var render_rooms = new Array();
req.app.settings.redis.lrange('rooms',0,-1, function(error, rooms) {
// Keep track of the number of rooms we have left to process.
var roomcount = rooms.length;
if (error) {
console.log('Error: '+ error);
}
else {
rooms.forEach(function(room){
console.log("room: " + room);
req.app.settings.redis.hgetall(room, function(error, roomdetails){
if (error) {
console.log('Error: '+ error);
}
else {
console.log("roomdetails: " + roomdetails.public);
if(roomdetails.public == "true"){
render_rooms.push(roomdetails.name);
}
// Render code moves to here and is only run after all rooms
// have been processed.
if (--roomcount === 0) {
console.log("length: " + render_rooms.length);
res.render('index', {
title: 'Index',
username: req.user.username,
rooms: render_rooms
});
}
}
});
});
}
});
};
Once you get comfortable with what this is doing, take a look at cleaning it up a bit by using async.forEach or async.forEachSeries which more cleanly support this type of flow.