使用node.js删除Mongo中Id的子文档

时间:2013-07-14 03:55:41

标签: node.js express coffeescript mongoose

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

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

1 个答案:

答案 0 :(得分:0)

如果您的意思是如何实现删除评论:首先使用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) { ... });