Node.js & Express From Scratch [Part 7] – Update & Delete Articles
- December 22, 2023
- Posted by: MainInstructor
- Category: Go JavaScript Node
Video Title: Node.js & Express From Scratch [Part 7] – Update & Delete Articles
Alright guys so we can now add articles we can view the listing listings and we can click on a single article so what I want to do now is add an edit button to this page the single article page so let’s go to views and then article dot
Pug and we’re going to go under the body and let’s put an HR and then we’ll put right under it for a tag let’s give it a class of BTN and BTN will say default and then it’s going to need an href and the href is going to go to slash
Articles or article slash edit slash and then the ID which we need to just concatenate on like that article dot underscore ID so let’s take a look at that oh we need to text okay so now we have an edit and you can see it goes to
Article edit and then the ID so we need to route for that let’s go back to our app dot j/s file okay and then this is going to be similar to the single article because we need to get the ID we need to find the that specific article
And then we need to load the edit form so I’m going to just copy this whole thing here and let’s paste it in we’ll go under the add ok so this will be load edit form so slash article slash edit / ID then we’re going to find it by its ID
Then we’re going to render a template called edit underscore article alright we’re going to pass along the article so let’s save that and then what we’ll do is copy what we have an add article could look it’s the same form we’ll copy that and then we’ll create another view
And we’ll call this edit on a score article dot pug and then we’ll paste that in okay Let’s see it has a title so let’s pass in a title and we’ll just say edit you don’t have to do this the dynamic title thing but I don’t know why not okay then we have our form now this form is going to go to a different place it’s going to
Go to articles slash edit slash and then the ID okay so we can get that with article ID or underscore ID sorry and then we need to put the values in these inputs so let’s add right here value equals and not exactly sure the syntax I
Think I think we might be able to just do article dot title like that let’s try it out so if we reload this we click Edit there we go yeah that works article one so we want to do the same thing for author okay and then for the text area
We actually want to put that here so article dot body all right if we reload now we have the data oh that’s not right let’s see it think that work yep let’s actually put a space right above the button there I don’t like that same thing with the ad all right so now
We have the form the edit form with the data inside of it now we need to catch the submission which is going to go to articles edit and then the ID it’s going to be a post request so let’s go to app J s and this is going to be similar to
The ad so let’s grab this paste that in and let’s say update submit so post and it’s going to go articles slash edit / : ID okay now this is going to work a little differently we’re not creating a new article what we’re going to do is
Set this to an empty object so we’ll say let article equals an empty object and then we’re going to add to it like this we can leave it we’re going to get the fields from the form add to that object and then we’re going to create a query
Because we need to specify which one we want to update we’re going to say we’re underscore ID matches request params dot ID okay which is going to be this coming in from the URL and then instead of using the actual article variable up here we’re going to use the model okay
So that’s capital a article and then it’s going to be update not saved okay and then we need to pass in first the query and then the data which is in an object in this article variable that we added all the stuff here and then the
Rest will be the same we’re just going to redirect so let’s save that and then we’re going to go to this thing here this is DD and let’s edit that we’ll say article 5 and submit and there we go so you can see it’s changed to article 5 so
We can now update articles so now we want to be able to delete them now delete is going to work differently because we want to make a delete request and we can’t do that with a simple link we can’t do that with by submitting a
Form you can only do get in post so what we have to do is use Ajax and there’s a lot of different options what I’m going to do is just use jQuery and then just make a simple delete request with Ajax to the delete route all right so we need
To create the button first so let’s go to our article dot pug and let’s put a link here and this is going to have a class let’s say BTN and then BTN danger alright and then the href is just going to go nowhere it’s going to go to a
Number side because what we’re going to do is add we’re going to add a class in addition to these button collapses called delete we’ll say delete – art or article alright and then we’re going to use that we’re going to grab onto that with jQuery and then we’re going to make
A delete request now remember we need to know the ID to make that request so what we can do is we can attach another attribute called data – ID and we’re going to set that equal to so you’re going to set that equal to article dot underscore ID oops
I’m not sure if I can do it that way but let’s let’s save that and take a look alright so if we do an inspection here let’s just check that ok so that is working you see data ID equals and then it’s the ID and then
We’ll be able to grab on to that from within jQuery and we’ll be able to make our request now the file that we’re going to use is going to be in the public folder so let’s say new folder in public called j/s and we’ll create a new
File called main jas so this is basically the client-side JavaScript file alright while we’re here let’s create a CSS folder as well and then a style sheet because we don’t have a custom style sheet yet alright and then we’re going to have to include both of those in our layout
Files so let’s go to layout pug and let’s copy this and paste that in and then we’re going to change this to slash CSS slash style.css and then we want the main j/s included down here okay after all this stuff so this will go to /j s
Which is in the public folder slash main j/s alright and just test it out let’s go to main js2 just do an alert ok and there we go we get the alert so we want to make our Ajax requests so we’re going to use jQuery so let’s do document dot
Ready and then put in function I do have a jquery crash course that you can check out if you want to learn more about jquery so let’s see we’re going to grab on to that delete article class okay and then we’re going to do dot on
And then click ok when it’s clicked on we’re going to run to function and it’s passed in here so that we can say e dot prevent actually no we don’t need to do that it’s not a form let’s but we do need to get the target okay
Because we want to be able to grab on to that data attribute that data ID so we can create a variable called target and set that to that event variable dot target and then we should be able to get the data ID attribute so let’s say
Console dot log and here we can say target dot adder and we want to get the data ID okay so let’s save that and we’re going to reload click on the console and then delete and you can see we’re getting that ID all right if we go to article
Three click delete we’re going to get that ID so now we can put that in a variable so say Const ID equals set it to that and then we can make our request so we’re going to say money sign Ajax and in here we’re going to pass in an
Object we want to say the type of request that this is going to be is a delete all right and then the URL is going to go to slash article /i whatever the idea is and remember we have that in a variable right here so we’re going to
Just concatenate that on alright then what we’ll do is right after this URL value we’re going to say success okay so if this works then we’ll get a response and actually let’s do like this all right so success and all we want to do is let’s do it we’ll do an alert and
We’ll say deleting to do what to do what the hell is this article and then we’re going to redirect to the home page and we can do that in JavaScript with window dot location dot href let’s do single quotes and we’ll go to slash alright and
Then if there’s an error then we want to run this function that will pass us an error message and we’ll console.log it alright so that should do it let’s save and now we need to create this route because this is what it’s going to be submitting the delete request to so
We’re going to go back to AB js’ and let’s go down here and we’re going to do AB delete okay cuz it’s a delete request and it’s going to go to slash article / : id class response just like any other type of request now to delete it we’re
Going to say X let’s create a query variable and we’re going to set underscore ID to request dot params ID which is coming from the URL and then we can take the model so article and we can say dot remove we can pass in the query and then the function alright we’ll put
An error here and we’ll just test for the error era now since we made a request from that main jf script we need to send back a response so to do that we’re just going to say res send and by default that’s going to send a 200 status which
Means everything’s ok so we can put a little message in here we’ll just say success okay so let’s save it and let’s go back over here and go to article 5 and click delete we get our alert click OK and it redirects us and you can see article 5
Is gone alright so I hope that wasn’t too confusing I know when I first started learning Express and all this stuff the delete requests really confused me you know making the Ajax request I did I couldn’t see why we can just create a link that would send it to
A get request and then delete it that way but that’s very very insecure so that’s going to be it guys for this video I’m not exactly sure what we’ll do next I do want to eventually deploy this application I might also add some authentication to it but we have a full
Crud functionality application and that’s it I will see you in the next video
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Spent so much time thinking why nothing was deleting, turns out, I hadn't connected main.js to the ejs file… GOD!!
nice, looking forward to see where it goes from here
Unable to update my database….got an error object.update is not a function
How could we handle a delete request with plain javascript and Ajax or some other async utility?
el codigo lo puede dejar igual en el app.js
este funciona correctamente para todos los para todos los navegares
$(document).ready(function () {
$('.delete-article').on('click', function(e){
$target = $(e.target);
const id = $target.attr('data-id');
$.ajax({
url: '/article/'+id,
data: {"_method":"delete"},
dataType:'script',
type:'POST',
success: function(result) {
alert('Deleting Article')
window.location.href='/';
},
error: function(err) {
console.log(err);
}
});
});
});
en algunos navegadores no funciona el DELETE dure casi un dia, para saber cual era la situacion
for anyone coming across this video from the time of this message remove is being deprecated please use deleteOne, deleteMany, or bulkWrite instead. the delete one follows as showing with the parms taken in I recommend checking if this is changed if you are seeing this comment in the future
I am unable to update my article, can somebody help?
why cant stupid people who designed html allows us to directly submit put and delete requests from html forms, what the helll is so wrong with that
HI! Thank you for great tutorial. I am learning with these videos. But in this part i encountered one problem. I followed all your instruction but after pressing Delete button, nothing isn't deleted and couldn't get to the home page. I have checked Chrome Console there is one error like this: $.ajax is not a function. I have installed ajax in node by "npm install ajax". What can I do? Thank in advance for your help!
If you want to avoid the use of ajax and jquery you can simulate a link within a form like this, i know Ruby On Rails does stuff like this under the hood hope it can help
form(method='POST', action="/articles/delete/"+ article._id)
input.btn.btn-outline-danger(type='submit', value='Delete')
cool
I have tried to redirect to the (just) updated post. I have run into an error. See topic here: https://stackoverflow.com/questions/56816720/express-js-crud-application-bug-update-function-does-wrong-redirect
Hey brad, As a junior level developer, for you, what kind of project/s app as a portfolio to apply a job?
Thanks man
Hi, I got a DeprecationWarning on post edit, has anyone got a similar problem: (node:10814) DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
Hi. Do you know how I can validate that if a schema has a field as a foreign key it does not allow me to delete the record?
Anyone who wants to do the delete without jQuery and Ajex, this works for me.
window.onload = () => {
const deleteButtonExists = document.body.contains(document.getElementById('delete'));
if(deleteButtonExists){
const deleteButton = document.getElementById('delete');
deleteButton.addEventListener('click', e => {
const articleToDeleteID = e.target.attributes['data-id'].value;
const xmlRequest = new XMLHttpRequest();
xmlRequest.open('DELETE', "/articles/delete/"+articleToDeleteID, false); //setting to false makes request synchronous, wait for response before continuing
xmlRequest.send();
window.location = '/';
});
}
}
how can i implement jquery in my js file? i watched every video until now in your playlist on youtube but if i type a $ in my main.js and hover over it with my mouse it just sais any (i am using visual studio code)
omg why the object isnt deleting while im pressing the button delete? Nothing even happens when im pressing it.can someone explain me why? what i have done wrong?
I don't GET (ah ah… GET) why you use Ajax to delete a document in the DB. Install method-override (it's on github), and just create a form with a method of type POST and action of '/'. Add "input(type='hidden', name='_method', value='delete')" inside the form to make a request of type DELETE. The hidden input will override the the current method, that way we can use any CRUD functions directly in the HTML. The app.js can stay the same and everything will work just fine.
I am at the deleting articles part, however, after following along and then pressing delete in my browser nothing happens except in the url after id the browser adds a #; again nothing happens. Any help would be greatly appreciated. Thank you.
for the delet fucntion when i click i delete i get
500 Internal error
Help, anyone?
We can use fetch keyword instead 😀 It's easier…
<a href="#" onclick="deleteArticle()" class="btn btn-danger " id="delete" foo = "<%=article._id%>" >Delete</a>
then under script tags…
function deleteArticle() {
let id = document.getElementById('delete').getAttribute('foo');
// Lets make a fetch delete request
fetch('/articles/delete/'+id,{
method : 'DELETE'
}).then( res => {
console.log('request successfull',res);
})
}
P.S. I used Ejs and you can correct me if i am wrong 🙂
Please tell me how to delete elements of Array of objects using mongoose
Please do a full tutorial on MySQL as well.
Please Brad! you go too fast not explaining details which variables are which. You just go straight. I don't understand anything.
While clicking Submit im Edit Activity it says cannot POST to /articles/edit/(id of article) what is will be the error?
I was getting the error "$.ajax is not a function", which is because jQuery-slim does not support ajax calls. To resolve, just use jquery-min instead of jquery-slim-min
"Uncaught ReferenceError: $ is not defined" i am getting this error pls help guys 🙁
@Traversy Media is there anyway to do the delete request without the ajax or Jquery?? because I cant get it to run on the client side .js properly? Really would appreciate the help!!!