使用mongoose使用索引值删除数组内的注释

我必须使用索引值删除第二条评论。以下是我的文档结构

{ "_id" : ObjectId("000000000fea5f24282e715b"), "file_name" : "resume_of_ganga_.docx", "created_date" : ISODate("2017-11-28T10:29:10.373Z"), "updated_date" : ISODate("2017-11-28T12:39:32.148Z"), "comments" : [ { "created_date" : ISODate("2017-11-28T13:23:51.472Z"), "status" : "N", "comment_text" : "Yes...", "username" : "name" }, { "created_date" : ISODate("2017-11-28T13:24:15.938Z"), "status" : "N", "comment_text" : "asdsd", "username" : "name" } ] } 

我已经使用这个mongoose查询..但我的意见是不会被删除

  mongo.filemanager.findOneAndUpdate({ "_id": req.body.id},{$pull : {"'comments.' +req.body.c_index" : 1 }},function(err,response){ console.log("Deleted") }); 

例如,我正在索引值为2 ..它应该删除第二个评论…

提前致谢

我试着查看MongoDB是否有这样的function,但似乎他们不是从我发现的。

解决方法可能是这样的。 不知道这是否可以被视为一个primefaces操作。

 const removeCommentAtIndex = (index) => { mongo.filemanager.findById(req.body.id, (err, file) => { file.comments.splice(index, 1); file.save(); }) } 

我执行了在mongoDb中接受的答案,如何通过在我的testing数据库中的索引来移除一个数组元素,而IT WORKS

 mongo.filemanager.findOneAndUpdate({}, {"$unset" : {"comments.1" : 1 }}) mongo.filemanager.findOneAndUpdate({}, {"$pull" : {"comments" : null}}) 

请注意,您的req.body.c_index需要是1才能删除第二条评论。