0

I am trying to delete elements after retrieving them from the database using mongoose. However i am stuck at a part where i do not know how to 'grab' one particular element in the list and then how to delete it.

In my app, i have a list of users and their age. Here is my userview.ejs (EDITED after adding frontend.js)

<meta charset="UTF8">
<link href="../public/javascripts/frontend.js">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="/stylesheets/userlist.css">
<link href='//fonts.googleapis.com/css?family=Amatic SC' rel='stylesheet'>
<link href='//fonts.googleapis.com/css?family=NTR' rel='stylesheet'>
<html>
    
    <head>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
        <title>Userlist</title>
        <script src="javascripts/frontend.js"></script>
     <script>
            
        </script> 
        
    </head>
   
    <div class="container-fluid">
            <div class="row">
                     <h1><strong>FORM</strong></h1>
                     <hr id="hr2" style="border: 6px solid palevioletred" >
                <div id="black">
                     <form class="form-horizontal" method="post" action="/users">
                        <fieldset>


                        <!-- Text input-->
                        <div class="form-group">
                          <label class="col-md-4 control-label" for="textinput">Name : </label>  
                          <div class="col-md-4">
                          <input id="textinput" name="name" placeholder="Enter Username" class="form-control input-md" type="text" value="Name" onfocus="if (this.value=='Name') this.value='';">

                          </div>
                        </div>

                        <!-- Text input-->
                        <div class="form-group">
                          <label class="col-md-4 control-label" for="textinput">Age : </label>  
                          <div class="col-md-4">
                          <input id="textinput" name="age" placeholder="Enter Age" class="form-control input-md" type="number">

                          </div>
                        </div>

                        <!-- Button -->
                        <!-- Button (Double) -->
                        <div class="form-group">

                          <div class="col-md-8">
                            <button id="singlebutton" name="button1id" class="btn btn-success">Add User</button>
                          </div>
                        </div>

            <body>

                 <h1><strong>USERS</strong></h1>
                 <hr id="hr1" style="border: 6px solid #7ec4ec;" >
                 <ul id="list" class="triangle">
                    <% for(var i=0; i<userlist.length; i++) {%>
                       <li><%= userlist[i].name %> : <%= userlist[i].age %> <a href="#" onclick="delete_element('<%= userlist[i]._id %>')" id="delete">Delete</a> ||  <a href="#" onclick="update_element()">Update</a></li>
                    <% } %>
                 </ul>
            </body>


                        </fieldset>
                    </form>
                </div>
                </div>
  </div>
</html>

EDIT:

This is my frontend.js

var $ = require('jquery');
function delete_element (userId) { 
     $.post('delete/user/',userId,function(){
         
         alert('Deleting....'); //For now i have just added an alert.
     }); 
}

This is my new users.js

'use strict'

var express = require('express');
var router = express.Router();
var User=require('../models/usermodel.js');
var $= require('jquery');
    
/* GET users listing. */


router.get('/', function(req, res, next) {
  User.find({},function(err,userModel){
      res.render('userview',{userlist:userModel});
  });
});


router.post('/', function(req, res, next) {
    
    var newUser = new User({
          name:req.body.name,
          age: req.body.age         
    });
    
    console.log(newUser);
    // save the user
    newUser.save(function(err) {
      if (err) throw err;

      console.log('User created!');
    });

});


router.post("delete/user/:id", deleteUser); 

function deleteUser(req,res){
    
    User.findById(req.params.id).remove().exec(function(err){
         if (!err) {
                console.log('Removed Successfully');
        }
        else {
                console.log('Error in removing the entry');
        }
    });
}


  /*
function delete_element(id){
    
        $('#delete').on("click",function(){
           $(this).parent().remove(); 
        });
      User.remove({_id: req.body.id }, function(err) {
        if (!err) {
                console.log('Removed Successfully');
        }
        else {
                console.log('Error in removing the entry');
        }
      
          }); 
} 
     */               



/*router.post('/', function(req, res, next) {
    userModel.update( {name: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )
   
});*/







module.exports = router;

1 Answer 1

1

Embed the user's _id in your delete link :

onclick="delete_element('<%= userlist[i]._id %>')"

This will produce :

onclick="delete_element('55510c6cf0e19f6414b30f97')"

and pass the user's _id to your delete function.

Edit

Okay so, apparently, you're trying to call a function defined on the server (Node), directly from your view (HTML). That's absolutely not how it works :)

onclick="delete_element()" is calling a function locally, in your browser. The console (F12) must yell error : delete_element is undefined.

So the way to go is the following :

1) Create a javascript function (not in Node, in your front-end application) that will call the server.

function delete_element (userId) { // This will be called on click and passed the user's _id
     $.post('delete/user/'+userId) // This calls the server. Todo : add a callback, etc.
}

2) Your Node server must have a corresponding route that will receive the call :

router.post("delete/user/:id", deleteUser); // This is reached when the client calls post('delete/user/1a2b3c4d'). The id is read with req.params.id

deleteUser = (req,res) => {
     User.findById(req.params.id)
         .remove()
         .exec( error => { // Reply to the client, otherwise the request will hang and timeout.
             if(error) return res.status(500).send(error);
             res.status(200).end()
         })
}

That's for the first question, please create a new question for the second one.

Sign up to request clarification or add additional context in comments.

10 Comments

still doesn't work. Is the delete_element () function correct?
Yean, the Mongoose call seems correct. What does your delete_element function look like (the front-side one, not the one in Node) ?
There is none like that.
or....... are you trying to call a function defined on the server (Node), directly from your view (HTML), without any other operation in-between?? O_o
i would say yes. Please guide me if that is absurd. Im relatively new to the field.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.