【问题标题】:How to Delete Comment from Post on Node, express and Mongoose and Ajax如何从 Node、express、Mongoose 和 Ajax 上的帖子中删除评论
【发布时间】:2020-07-18 08:46:18
【问题描述】:

我需要有关如何从帖子中删除单个评论的帮助。当我点击删除它返回500 error。这里让我感到困惑的一些事情是,如果我在链接上同时传递帖子和评论 ID,我将如何告诉 Ajax 这个是用于发布的,而这个是用于评论的。 这是我的帖子架构

 const postSchema = new mongoose.Schema({
    title: {
       type: String,
       required: true
    },
    description: {
      type: String,
      required: true
    },
   from: {
      type: String,
      required: true
   },
   createdAt: { 
     required: true, 
     default: Date.now
  },
  postImage: {
    type: String,
    require: true
  },
  comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }]

 })

这是我的 main.js 文件中的 ajax。

/deleting comment with Ajax
$(document).ready(function() {
  $('.delete-comment').on('click', function(e) {
    const $target = $(e.target);
    const id = $target.attr('data-id');
    $.ajax({
        type: 'DELETE',
        url: '/posts/comments/'+id,
        success: function(response) {
            window.location.href='/posts';
        },
        error: function(err){
            console.log(err);
        }
    });
  }); 
});

我的路线/cmets

//Delete comment inside a post
router.delete( '/comments/:id', function( req, res ){
  const post = Post.findOne({_id: req.params.postId});
  const ObjectId = mongoose.Types.ObjectId;

  let query = {_id:new ObjectId(req.params.id)}
  console.log(query)

  post.comments.delete(query, function(err) {
    if(err){
     console.log(err);
   }
   res.send('Success');
 });
})

我的意见/index.ejs

 //Comments and link
<% const counter = post.comments.length >= 2 ? "Comments" : "Comment"; %>
<button class="show-comments"><%= post.comments.length + " " + counter + "" %></button>
<% %>
<div class="postcomments" ><% post.comments.forEach(item => { %>
  <ul >
    <li><%= item.description %></li>
    <a class="delete-comment" href="#" data-id="<%=item._id%>">Delete</a>

 </ul>
<% });%>

我的 app.js

//use route from app.js 
var commentRouter = require('./routes/comments');
app.use('/posts', commentRouter);

这是我的终端上返回的内容

DELETE /posts/comments/5e8ad7121277855e656b3379 500 5.395 ms - 3698

【问题讨论】:

  • 我们如何知道您要删除哪条评论?为此,您需要 postId 和 commentId 吗?您还可以将您的帖子架构添加到问题和示例文档中吗?

标签: node.js ajax express mongoose


【解决方案1】:

您需要知道 postId 和 commentId 才能从帖子集合中删除评论。另外最好删除 cmets 集合中的评论。

因此,更改您的删除路线以将 postId 和 commentId 包含为 req.params。 您可以使用findByIdAndUpdate 方法和$pull 运算符从帖子中删除评论。

router.delete("/comments/:postId/:commentId", async function (req, res) {
  try {
    const post = await Post.findByIdAndUpdate(
      req.params.postId,
      {
        $pull: { comments: req.params.commentId },
      },
      { new: true }
    );

    if (!post) {
      return res.status(400).send("Post not found");
    }

    await Comment.findByIdAndDelete(req.params.commentId);

    res.send("Success");
  } catch (err) {
    console.log(err);
    res.status(500).send("Something went wrong");
  }
});

测试

假设我们有这个包含 3 个 cmets 的 post 文档。

帖子:

{
    "_id" : ObjectId("5e8b10c49ae619486094ed10"),
    "comments" : [
        ObjectId("5e8b104f9ae619486094ed0d"),
        ObjectId("5e8b10599ae619486094ed0e"),
        ObjectId("5e8b105e9ae619486094ed0f")
    ],
    "title" : "Title",
    "description" : "Description...",
    "from" : "From",
    "postImage" : "Post Image",
    "createdAt" : ISODate("2020-04-06T14:21:40.884+03:00")
}

评论:

{
    "_id" : ObjectId("5e8b105e9ae619486094ed0f"),
    "message" : "Comment 3"
},

{
    "_id" : ObjectId("5e8b10599ae619486094ed0e"),
    "message" : "Comment 2"
},
{
    "_id" : ObjectId("5e8b104f9ae619486094ed0d"),
    "message" : "Comment 1"
}

如果我们想删除_id:5e8b10599ae619486094ed0e的评论,我们需要使用这样的url向我们的路由发送一个DELETE请求:

http://localhost:3000/posts/comments/5e8b10c49ae619486094ed10/5e8b10599ae619486094ed0e

5e8b10c49ae619486094ed10 是 postId,5e8b10599ae619486094ed0e 是 commentId。

结果会是这样的:

帖子:

{
    "_id" : ObjectId("5e8b10c49ae619486094ed10"),
    "comments" : [
        ObjectId("5e8b104f9ae619486094ed0d"),
        ObjectId("5e8b105e9ae619486094ed0f")
    ],
    "title" : "Title",
    "description" : "Description...",
    "from" : "From",
    "postImage" : "Post Image",
    "createdAt" : ISODate("2020-04-06T14:21:40.884+03:00")
}

评论:

{
    "_id" : ObjectId("5e8b105e9ae619486094ed0f"),
    "message" : "Comment 3"
},
{
    "_id" : ObjectId("5e8b104f9ae619486094ed0d"),
    "message" : "Comment 1"
}

【讨论】:

  • @SuleymanSah非常感谢您花时间向我解释它是如何工作的,我真的很感激。我用你上面给我的代码完全按照你说的做了,并更改了我的链接以包含这样的帖子 ID ` 删除 `一切都是
【解决方案2】:

您的 nodejs/express 路由包含此代码。也许它应该对可能的错误做更多的事情:具体来说,将错误传递给next() 函数,它是任何路由处理程序的第三个参数。

post.comments.delete(query, function(err) {
    if(err){
         console.log(err)
         return next(err)
     }
     res.send('Success')
});

将错误值传递给next() 应该将错误消息传递给用户。而且,您的服务器的 console.log 上会显示相同的消息。因此,如果错误来自那里,您应该了解更多信息。

【讨论】:

    【解决方案3】:

    我面临同样的问题除了在删除帖子之前,我想确保删除帖子的用户是同一帖子的创建者。我的数据集有点不同。

    import mongoose from 'mongoose'
    
    const postSchema = mongoose.Schema(
      {
        title: {
          type: String,
          required: true,
        },
        comment: { type: String, required: true },
        user: {
          type: mongoose.Schema.Types.ObjectId,
          required: true,
          ref: 'User',
        },
        imagePost: { type: String, required: true },
      },
      {
        timestamps: true,
      }
    )
    
    const stationSchema = mongoose.Schema(
      {
        user: {
          type: mongoose.Schema.Types.ObjectId,
          required: true,
          ref: 'User',
        },
        nameUnit: {
          type: String,
          required: true,
        },
        typeOfPoint: { type: String },
        image: {
          type: String,
          required: true,
        },
        lat: {
          type: Number,
          required: true,
        },
        long: {
          type: Number,
          required: true,
        },
    
        // Base
        nameBase: { type: String, required: true },
        element: {
          type: String,
          required: true,
        },
        baseCommanderInfo: { type: String },
        aboutBaseInfo: { type: String },
    
        // Unit
        unitSuperviserInfo: { type: String },
        unitCommanderInfo: { type: String },
        unitInfo: { type: String },
        taskInfo: { type: String },
        benefitInfo: { type: String },
    
        // address
        country: { type: String },
        province: { type: String },
        town: { type: String },
        adresse: { type: String },
        postalCode: { type: String },
    
        posts: [postSchema],
      },
      {
        timestamps: true,
      }
    )
    
    const Station = mongoose.model('Station', stationSchema)
    
    export default Station
    

    节点控制器

    const removeStationPost = asyncHandler(async (req, res) => {
      const stationId = req.params.id
      const postId = req.params.idPost
      const userId = req.user._id
    
      console.log(stationId)
      console.log(postId)
      console.log(userId)
    
      const station = await Station.findById(stationId)
    
      if (station) {
        station.posts.pull(postId)
        await station.save()
        res.status(201).json({ message: 'Post removed' })
      } else {
        res.status(404)
        throw new Error('Post not found')
      }
    })
    

    所以现在每个人都可以使用 Postman 删除任何其他人的帖子

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 2016-08-09
      • 2019-09-01
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多