gpt4 book ai didi

javascript - Mongoose - 删除选定的元素

转载 作者:行者123 更新时间:2023-11-28 04:40:17 25 4
gpt4 key购买 nike

在表中显示 Mongoose 的数据。如何使删除按钮正常工作,从表格中删除选定的元素

index.html

<div class="col-md-12 column list-group">
{% for note in notes %}
<div class="list-group-item">
<div>Note from <em><strong>{{ note.memberName }}</strong></em> on: {{ note.createdOn.toDateString() }}``
- for project: <strong>{{ note.project }}</strong></div>
<div><strong>Work yesterday:</strong> {{ note.workYesterday }}</div>
<div><strong>Work today:</strong> {{ note.workToday }}</div>
<div><strong>Impediment:</strong> {{ note.impediment }}</div>

<form action="/delete" method="post">
<button class="btn btn-danger" type="submit">DELETE</button>
</form>
</div>
{% endfor %}

index.js

router.post('/delete', function(req, res, next) {
var id = req.body.id;
Standup.findByIdAndRemove(id).exec();
res.redirect('/');
});

image preview

最佳答案

目前尚不清楚,但根据您提供的代码,您似乎没有将要删除的注释的 ID 发送到服务器。一种方法是添加一个隐藏的表单字段,其中包含 id 注释的值。例如,您的表单可能如下所示(假设您可以在客户端访问 note.id:

<form action="/delete" method="post">
<input type="hidden" name="id" value="{{ note.id }}">
<button class="btn btn-danger" type="submit">DELETE</button>
</form>

这样,当您提交表单时,您将在服务器的请求正文中发送该注释 ID 的值,并能够从 req.body 访问它。

正如其他答案所提到的,您还应该提供一个回调作为 findByIdAndRemove 的第二个参数,因为它是异步的。例如:

router.post('/delete', function(req, res, next) {
var id = req.body.id;
Standup.findByIdAndRemove(id, function (err, deletedStandUp) {
// handle any potential errors here
res.redirect('/');
});
});

这样,在删除完成或抛出错误之前,您的重定向不会发生。因此,当您的 '/' 路线呈现时,它将具有最新数据。

最后,我还建议让您的路由更加 RESTful,并使用方法 DELETE 并使路由名称与该 Controller 方法处理的资源相关(在本例中为 >/note。但是这并不需要解决您当前的问题。

关于javascript - Mongoose - 删除选定的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43851589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com