如何在express中使用特定的mongodb _id作为参数重定向按钮

6ie5vjzr  于 2023-05-06  发布在  Go
关注(0)|答案(1)|浏览(118)

我尝试使用_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
deyfvvtc

deyfvvtc1#

您可以简单地将事件侦听器添加到按钮并处理click事件:

<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>

相关问题