How to redirect button in express using specific mongodb

编程入门 行业动态 更新时间:2024-10-02 16:19:44

How to redirect <a href=https://www.elefans.com/category/jswz/34/1770590.html style=button in express using specific mongodb"/>

How to redirect button in express using specific mongodb

我正在尝试使用

_id
字段更新我在 MongoDB 中的数据,这是执行此操作的 HTML 按钮:

<form action="/update/:_id" method="get" id="edit-button">
  <button class="btn btn-success" type="submit" id="edit-button">
    Edit Post
  </button>
</form>

这是我的 Express 服务器的代码

app.js

app.get('/update/:_id', function (req, res) {
  const updateId = req.params._id;
  Post.findOne({ _id: updateId })
    .then((Posts) => {
      res.render('update', {
        updatedTitle: Posts.title,
        updatedContent: Posts.content,
        id: updateId,
      });
    })
    .catch((err) => {
      console.log(err);
    });
});

app.post('/update', function (req, res) {
  // const updateId = req.params.updateId;
  const updatedTitle = req.body.updatedTitle;
  const updatedContent = req.body.updatedContent;
  const updateId = req.body.id;

  post
    .findByIdAndUpdate(
      { _id: updateId },
      {
        title: updatedTitle,
        content: updatedContent,
      }
    )
    .then(() => res.redirect('/'));
});

这是我的视图模板的代码

update.ejs

<form action="/update" method="get">
  <div class="mb-3">
    <label for="titleInput" class="form-label">Title</label>
    <input
      type="text"
      class="form-control"
      name="updatedTitle"
      value="<%= updatedTitle %>"
      required
    />
  </div>
  <div class="mb-3">
    <label for="postArea" class="form-label">Post</label>
    <textarea
      class="form-control"
      rows="5"
      name="updatedPost"
      value="<%= updatedContent %>"
      required
    ><%= updatedContent %></textarea>
  </div>
  <button
    class="btn btn-primary update"
    type="submit"
    name="id"
    value="<%= id %>"
  >
    Update
  </button>
</form>

当我尝试直接访问链接时,它工作正常。例如:

http://localhost:3000/update/644a6d4c6fbe854da2375c61
。但是,当我尝试按下按钮或摆弄代码时,它会出现以下错误之一:

无法获取/更新

或在控制台中:

CastError: Cast to ObjectId failed for value ":_id" (type string) at
path "_id" for model "Post" and BSONError: Argument passed in must be
a string of 12 bytes or a string of 24 hex characters or an integer
回答如下:

你可以简单地给按钮添加一个事件监听器并处理点击事件:

<script>
  const editButton = document.getElementById('edit-button');
  editButton.addEventListener('click', () => {
    fetch(`http://localhost:3000/update/${whatever-the-id}`)
      .catch(error => console.log(error));
  })
</script>


<button class="btn btn-success" type="button" id="edit-button">
  Edit Post
</button>

更多推荐

How to redirect button in express using specific mongodb

本文发布于:2024-05-30 13:30:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770546.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:button   redirect   express   mongodb   specific

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!