2

I am showing data of several users in my application where there is a functionality of edit and delete of individual record.I am using Node express framework and using MongoDb as a database.My problem is when I am deleting any specific record then all the records are deleting from the table and when I am showing the result in console it is showing only that record on which I intended to delete.

Below is my code:

index.ejs

div class="container">

 <% if(users.length>0) {%>

    <p>Total available users - <%= users.length  %> </p>

   
      <table class="table">

        <thead class="thead-dark">
          <tr>
            <th scope="col">Name</th>
            <th scope="col">Email</th>
            <th scope="col">City</th>
            <th scope="col">Action</th>
          </tr>
        </thead>


        <tbody>
         <%  for(var i=0;i<users.length;i++) { %>
           <tr>
            <td><%= users[i].name %></td>
            <td><%= users[i].email %></td>
            <td><%= users[i].city %></td>
            <td><a href="/edit/<%= users[i]._id %>">Edit</a> | <a id = "del" href="/delete/<%= users[i]._id %>"> Delete </a> </td>
           </tr>
         <% }  %>  
        </tbody>
      
      </table>

  
  <% } else{ %>

     <p>No data found</p>
 <%  }  %>  

</div>

This yields below ui:

enter image description here

Student.js Schema

const mongoose = require('mongoose');

const studentSchema = new mongoose.Schema({

  name:{
    type:String,
    required:true
  },
  email:{
    type:String,
    required:true
  },
  city:{
    type:String,
    required:true
  },
  timeCreated:{
    type:Date,
    default:()=>Date.now()
  }
});

module.exports = mongoose.model('Student',studentSchema);

server.js

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Student = require('./models/Student');
const dotEnv = require('dotenv').config();
const cors =  require('cors');

const app = express();

const port = process.env.PORT || 3000;

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));


app.set('views', path.join(__dirname, 'views'));
app.set('view engine','ejs');

app.use("/public", express.static('public')); 
app.use(express.static(path.join(__dirname,'public')));

app.get('/delete/:id',(req,res) => {

mongoose.connect(process.env.URI,{useNewUrlParser:true,
        useUnifiedTopology:true}).then(() =>

            Student.findOneAndDelete(req.params.id, (err,result) => {

                if(err){
                    console.log("Error",err);
                }
                else{
                    res.redirect('/');
                    console.log(result + " - " + req.params.id);
                }
            })
         
         ).catch((err) => console.log(err));

});

app.listen(port,() => console.log(`App is running at ${port}`));

Someone let me know why all the records are deleting instead of one which I want to delete.

2 Answers 2

4

Mongoose offers two similar methods: findOneAndDelete which takes JavaScript object representing query as first parameter or findByIdAndDelete which can take ObjectId as first parameter. Therefore you can change your code into:

Student.findOneAndDelete({ _id: req.params.id }, (err,result) => {

or

Student.findByIdAndDelete(req.params.id, (err,result) => {

Also make sure that types match - if req.params.id comes as string and you store your ids as ObjectId then you need to convert them (example here).

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

Comments

0

can you try delete request instead of get

app.delete('/delete/:id',(req,res) => {
mongoose.connect(process.env.URI,{useNewUrlParser:true,
useUnifiedTopology:true}).then(() =>

        Student.findOneAndDelete({_id: req.params.id}, (err,result) => {

            if(err){
                console.log("Error",err);
            }
            else{
                res.redirect('/');
                console.log(result + " - " + req.params.id);
            }
        })
     
     ).catch((err) => console.log(err));

});

<td><a href="/edit/<%= users[i]._id %>">Edit</a> | <form action="/delete/<%= users[i]._id %>" method="POST">
  <input type="hidden" name="id" value="<%= users[i]._id %>"/>
  <button>DELETE</button>
</form></td>

Comments

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.