how to update by using id in express js and mongoose with parameters

Viewed 384

This is how my data look from frontend from mongodb

this is my ejs code which on clicked on update uses the item.id on url

<div class="header">
    <a href="./viewdatabase">Get Details in json format</a>
    <a href="./getdetails">refresh</a>
</div>
<hr>

<% if(details!=null) { %>
    <table id="bordertable">
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Gender</th>
            <th>Locality</th>
            <% details.forEach((item)=>{ %>
        <tr>
            <td>
                <%= item.name%>`enter code here`
                <a href="/update/<%= item._id %>" >update</a>
            </td>
            <td>
                <%= item.age %>
            </td>
            <td>
                <%= item.gender%>
            </td>
            <td>
                <%= item.locality%>
            </td>

        </tr>
        <% }) %>
    </table>
    <% } %>

my index.js

    app.get('/update/:id', (req, res) => {    
    var id = req.params.id; 
       res.render('edit.ejs');  
       console.log(req.params.id);
    });

    app.post('/edit',(req, res) => {
     gymApplicant.updateOne({ _id:req.params.id }, {$set: {
        age: req.body.age,
        gender:req.body.gender
     }
     }, function (err, result) {
          if (err) {
          console.log(err);
        } else {
         console.log("Post Updated successfully");
         res.render('abc.ejs');
     }
    });
    });

which on click on update it redirects to a form to update the age but when i send post request it says not defined because id is out of scope so any idea how to solve this issue.

Thanks in advance

0 Answers
Related