Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

javascript - How to delete data from mongoose collection by onclick?

I am new to mongodb, and I have created a todo list app using mongodb as a database. When user types something it saves to the mongoose collection, But when I try to delete the data from mongoose collection by onclick, It goes in order like If I click on the second button it will delete me the first data then second data and then third, It doesn't matter which button i am clicking It always goes in order(1,2,3,etc...)

Here is my code

app.js

router.delete('/Delete_Data',  (request, response) => {
    item.findOneAndDelete({}, (err, data) => {
        if(err){
            console.log(err);
            return response.status(500).send();
        }
        else{
            return response.json({data});
        }
    });
    
});

script.js

async function deleteLSItem(){
  
  let options = {
    method: 'DELETE',
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const response = await fetch('/Delete_Data' , options);
  const data = await response.json();
  console.log(data);
}

deleteLSItem() is a delete button

<td class="table-buttons" id="margin-padding"><button class="btn btn-sm btn-primary delete-btn" onclick="deleteLSItem()"><i class="fa fa-trash" aria-hidden="true"></i></button><span>Delete</span></td>

Here is the output

question from:https://stackoverflow.com/questions/65889230/how-to-delete-data-from-mongoose-collection-by-onclick

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
router.delete('/Delete_Data',  (request, response) => {
item.findOneAndDelete({'_id':9898}, (err, data) => {
    if(err){
        console.log(err);
        return response.status(500).send();
    }
    else{
        return response.json({data});
    }
});

});

By specifying fliter in item.findOneAndDelete({}... by '{}' You 're deleting the first item in the collection. Let's say id of the item that you want to delete is 9898. Then your code should look like above

see https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/index.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...