2016-09-10 14 views
1

--NodeJS、マングース、MongoDBは、ExpressJS、EJS--マングースのMongoDBは、アレイ上の要素を削除

私のウェブサイトがあり、彼らは「名前」と「画像」を提出することができますログインユーザが、そこにあります彼らが望むもののうち、著者や他の人々がその写真にコメントすることができます。各画像ごとに、私は画像上のコメントを数えている.length関数を使ってコメントをカウントし、コメント数を自分のejsファイルに投影する関数を追加しました。ここ

は私のスキーマです:、私はユーザーにコメントを削除する機能を持っている

var testSchema = new mongoose.Schema({ 
    name: String, 
    image: String, 
    author: { 
     id: { 
      type: mongoose.Schema.Types.ObjectId, 
      ref: "Loginuser" 
     }, 
      username: String 
    }, 
    comments: [ 
     { 
     type: mongoose.Schema.Types.ObjectId, 
     ref: "Comment" 
     } 
    ] 
}); 

var commentSchema = new mongoose.Schema ({ 
    author: { 
     id: { 
      type: mongoose.Schema.Types.ObjectId, 
      ref: "Loginuser" 
     }, 
     username: String 
    }, 
    text: String, 
    date: String 
}); 

var loginSchema = new mongoose.Schema ({ 
    username: String, 
    password: String 
}); 


var TestData = mongoose.model("User", testSchema); 
var Comment = mongoose.model("Comment", commentSchema); 
var LoginUser = mongoose.model("Loginuser", loginSchema); 

app.delete("/index/:id/comments/:comment_id", function(req, res){ 
    Comment.findByIdAndRemove(req.params.comment_id, function(err){ 
     if(err) { 
      console.log(err); 
      res.redirect("/index/"); 
     } else { 
      console.log("Comment successfully deleted!"); 
      res.redirect("back"); 
     } 
    }); 
}); 

ここに私のMongoDB commentSchemaからいくつかのサンプルデータは

{ "_id" : ObjectId("57d316e506d8e9186c168a49"), 
    "text" : "hey baby! why cry?", " 
__v" : 0, 
    "author" : { "id" : ObjectId("57d148acd0f11325b0dcd3e6"), 
    "username" : 
    "nagy" }, 
    "date" : "9/10/2016 , 8:07 AM" } 

{ "_id" : ObjectId("57d316f706d8e9186c168a4a"), 
    "text" : "don't you cry baby!", 
"__v" : 0, 
    "author" : { "id" : ObjectId("57d095d727e6b619383a39d0"), 
    "username": "doge" }, 
    "date" : "9/10/2016 , 8:07 AM" } 

{ "_id" : ObjectId("57d3170306d8e9186c168a4b"), 
    "text" : "wow so cute!!!!!!", "_ 
_v" : 0, 
"author" : { "id" : ObjectId("57d095d727e6b619383a39d0"), 
"username" : "doge" }, "date" : "9/10/2016 , 8:07 AM" } 
です

と私のデータはこちらあなたが見ることができるようにtestSchema

{ "_id" : ObjectId("57d316c506d8e9186c168a47"), 
     "name" : "Baby crying", 
     "image": "https://s-media-cache-ak0.pinimg.com/564x/d0/bb/ed/d0bbed614353534df9a3be0abe 
    5f1d78.jpg", 
     "comments" : [ ObjectId("57d316e506d8e9186c168a49"), ObjectId("57d3 
    16f706d8e9186c168a4a") ], "author" : { "id" : ObjectId("57d095d727e6b619383a39d0 
    "), "username" : "doge" }, "__v" : 2 } 

{ "_id" : ObjectId("57d316dc06d8e9186c168a48"), 
    "name" : "Maria?! OZawa?!", 
    "image" : "https://dncache-mauganscorp.netdna-ssl.com/thumbseg/1092/1092126-bigthumb 
nail.jpg", 
    "comments" : [ ObjectId("57d3170306d8e9186c168a4b") ], "author" : { " 
id" : ObjectId("57d148acd0f11325b0dcd3e6"), "username" : "nagy" }, "__v" : 1 } 

に、testSchemaとcommentSchemaにコメントのOBJECTIDは同じです。基本的には関連している。

正常に動作しています。コメントを削除しています。ここでの問題は、「コメント」モデルでのみ削除されていることです。

「TestData」モデルでも同じコメントを削除したいと思います。なぜなら、コメントを削除するたびにコメント数が変わらないからです。

両方のモデルでその特定のコメントを削除します。

私は、このアプローチを使用してみました:

app.delete("/index/:id/comments/:comment_id", function(req, res){ 
     TestData.findByIdAndRemove(req.params.comment_id)function(err){ 
     if(err) { 
      console.log(err); 
      res.redirect("/index"); 
     } else { 
      res.redirect("back"); 
     } 
    }); 
}); 

が、それは動作しません。

私はどのような特定のクエリを使用すべきですか?

更新:私はプレミドルウェアを追加しましたが、まだ動作していません。間違っている可能性があります。私はpreミドルウェアを "app.delete"の上に置きました。あれは正しいですか?

commentSchema.pre('remove', function (next) { 
    User.update(
    { comments: this }, 
    { $pull: { comments: this._id } }, 
    { multi: true } 
).exec(next) 
}); 

app.delete('/index/:id/comments/:comment_id', function (req, res) { 
    Comment.findById(req.params.comment_id, function(comment){ 
     comment.remove(); 
     console.log("comment succesfully deleted!"); 
     res.redirect("back"); 
    }); 
    }); 

鉱山と同様の問題があるstackoverflowのthrought読んだ後、私は...あまりにも同様の事前ミドルウェアを、このいずれかを試してみたが、それは「更新」を使用しています。

commentSchema.pre('update', function (next) { 
    this.model('User').update(
    { comments: this }, 
    { $pull: { comments: this._id } }, 
    { multi: true } 
).exec(next) 
}); 

app.delete('/index/:id/comments/:comment_id', function (req, res) { 
    Comment.findById(req.params.comment_id, function(comment){ 
     comment.update(); 
     console.log("comment succesfully deleted!"); 
     res.redirect("back"); 
    }); 
    }); 

とええ、まだ手動配列からコメントIDを削除する必要があります:(

答えて

1

を働いていないこれを行うには良い方法は、あなたのコメントのスキーマにremove middlewareを追加します。

commentSchema.pre('remove', function (next) { 
    User.update(
    { comments: this }, 
    { $pull: { comments: this._id } }, 
    { multi: true } 
).exec(next) 
}) 

しかし、削除するミドルウェアはdoc.removeを呼び出すことによってのみ実行され、Model.findByIdAndRemoveでは実行されません。つまり、あなたのコード(私は読みやすくするために、ここで約束を使用していますが、あなたはコールバックでこれを行うことができます)を少し変更する必要があります。

app.delete('/index/:id/comments/:comment_id', function (req, res) { 
    Comment.findById(req.params.comment_id) 
    .then(function (comment) { 
     return comment.remove() // doc.remove will trigger the remove middleware 
    }) 
    .then(function() { 
     console.log('Comment successfully deleted!') 
     return res.redirect('back') 
    }) 
    .catch(function (err) { 
     console.log(err) 
     res.redirect('/index') 
    }) 
}) 
+0

私はコードでこれを貼り付けしようとしたが、それは私にエラーを与えています"予期しないトークン"の – John

+0

あなたのコードを編集しました。 "コメントスキーマ。 ._id}}、 {マルチ:true} ).exec(次) }); app.delete( '/インデックス/:ID /コメント/:comment_id'、関数(REQ、RES){ Comment.findById(req.params.comment_id、関数(ERR){ \t IF(ERR){ \t \tにconsole.log(ERR); \t}他{ \t \tリターンcomment.remove(); \t \tはconsole.log( "正常に削除されたコメント!"); \t \t res.redirect( "バック") ; \t} }); }); 「エラーは」コメント「isnt define」on comment.remove() " – John

+0

" app.delete( '/ index /:id/comments /:comment_id'、function(req、res){ Comment.findById(req。 params.comment_id、関数(ERR){ \t IF(ERR){ \t \tにconsole.log(ERR); \t}他{ \t \t戻りcomment.remove(); \t \tはconsole.log( "コメント正常に削除された "); \t \t res.redirect("!バック "); \t} }); });' "コメント" DEFIではありませんcomment.remove()にありがとうございます。どうすれば修正できますか? – John

関連する問題