【问题标题】:Deleting a subdocument by Id in Mongo using node.js使用node.js在Mongo中按Id删除子文档
【发布时间】:2023-03-08 01:34:01
【问题描述】:

我正在使用 nodejs、express、mongo 和 coffeescript,我有一篇关于 cmets 的简单博客文章,我想添加在任何给定时间删除特定评论的可能性。架构如下所示:

Schema = mongoose.Schema

ArticleSchema = new Schema
  title:
    type: String
    trim: true
    required: true

  body:
    type: String
    required: true

  createdAt:
    type: Date
    default: Date.now

  comments: [
    body:
      type: String
      default : ''

    user:
      type: Schema.ObjectId
      ref: 'User'
      required: true

    createdAt:
      type: Date
      default: Date.now
  ]

文章的路线映射如下:

 articles = require '../app/controllers/articles'
 app.get '/', articles.index
 app.get '/articles', articles.manage
 app.get '/articles/new', auth.requiresLogin, articles.new
 app.get '/articles/:articleId', articles.show
 app.get '/articles/:articleId/edit', auth.requiresLogin, articles.edit

 app.param 'articleId', articles.article

但是我该如何做这样的事情才能删除评论呢?

  app.get '/articles/:articleId/comment/:commentId/delete', auth.requiresLogin, articles.edit

【问题讨论】:

    标签: node.js express coffeescript mongoose


    【解决方案1】:

    如果你的意思是你应该如何实现删除评论:你首先使用articleId检索文章文档,然后你可以找到并删除子文档:

    // find article
    ...
    
    // find the comment by id, and remove it:
    article.comments.id(commentId).remove();
    
    // since it's a sub-document of article, you need
    // to save the article back to the database to
    // 'finalize' the removal of the comment:
    article.save(function(err) { ... });
    

    【讨论】:

    • 感谢@robertklep 的回答,但是如何使用 app.param 将 :commentId 定义为路由参数?
    • 再想一想,我认为实际上不需要它;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2019-07-03
    相关资源
    最近更新 更多