2013-07-14 59 views
0

我正在使用nodejs,express,mongo和coffeescript,並且我有一個簡單的帶有註釋的博客帖子,我想添加刪除任何給定註釋的可能性時間。該模式是這樣的:使用node.js在Mongo中使用Id刪除子文檔

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 

回答

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) { ... }); 
+0

謝謝你的回答@robertklep,但我將如何使用app.param將:commentId定義爲路由參數? –

+0

第二個想法,我不認爲它實際上需要;-) –

相關問題