Home > Enterprise >  mongoose deleteone resulted 0
mongoose deleteone resulted 0

Time:11-09

please help. I'm new on node.js. i use mongoose to delete record on mongodb

this is my record

    MongoDB Enterprise > db.contacts.find().toArray();
[
        {
                "_id" : ObjectId("6187ebca4691bb4a3eeeb91d"),
                "nama" : "herahadi",
                "notlp" : "084234234234",
                "email" : "[email protected]",
                "__v" : 0
        },
        {
                "_id" : ObjectId("618861aaeeb7aeaf202a1890"),
                "nama" : "izam",
                "notlp" : "08533523232323",
                "email" : "[email protected]",
                "__v" : 0
        }
]

my app.js

    var methodOverride = require('method-override');    
    .....
    app.delete('/contact',async(req,res)=>{
    console.log('req.body.nama='  req.body.nama);

    Contact.deleteOne({ nama: req.body.nama }).then((result)=>{
        console.log(result);
        res.redirect('/contact');
    });

and this is page that call the delete

<form method="POST" action="/contact?_method=DELETE" class="d-inline">
                    <input type="hidden" name="nama" value="<%= contact.nama %> ">

if i run my project on console log i got this result

req.body.nama=izam 
{ deletedCount: 0 }

can someone tell me what is wrong?

CodePudding user response:

If you want to return deleted value result, then you should use Mongoose | findOneAndDelete() Function.

The findOneAndDelete() function is used to find a matching document, remove it, and pass the found document (if any) to the callback.

https://www.geeksforgeeks.org/mongoose-findoneanddelete-function/

CodePudding user response:

i solved my problem by change to findOneAndDelete() as mentioned by @Naveem. but also have to change req.body.nama into JSON.stringify(req.body.nama) otherwise its still can't delete the record.

so here is my final code

app.delete('/contact',(req,res)=>{
    console.log('req.body.nama='  req.body.nama);
    // const contact = await Contact.findOne({nama:req.body.nama});

    Contact.findOneAndDelete({ nama: JSON.stringify(req.body.nama) }).then((result)=>{
        
        console.log(result);
        res.redirect('/contact');
    });

CodePudding user response:

Please check both code and the attached screenshot for results. Screenshot for the terminal result from mongoose query with full user result 1st image https://i.stack.imgur.com/SrGyL.png

Nodejs code script for find one and delete 2nd image https://i.stack.imgur.com/IWN9p.png

  • Related