简体   繁体   English

如何从Mongo中的数组中删除元素

[英]How to remove an element from an array within Mongo

I'm completely stuck with Mongoose and remove method. 我完全陷于Mongoose和删除方法。 I have a page with comments and form with a button Delete . 我有一个带有注释的页面和带有“ Delete按钮的表单。 My goal is to delete only that comment which was clicked. 我的目标是仅删除单击的评论。 Below is my MongoDB file (By the way I use method override of the express library to handle both request post and delete). 以下是我的MongoDB文件(通过我使用express库的方法override来处理请求发布和删除的方式)。



{
    "_id": {
        "$oid": "5a455cf460414f548f3d1afb"
    },
    "title": "Tets",
    "body": "tes",
    "user": {
        "$oid": "5a440bae124b7e4626aeeb70"
    },
    "date": {
        "$date": "2017-12-28T21:07:00.194Z"
    },
    "comments": [
        {
          "commentBody": "ets",
          "commentUser": {
                "$oid": "5a440bae124b7e4626aeeb70"
            },
            "_id": {
                "$oid": "5a455cf660414f548f3d1afc"
            },
            "commentDate": {
                "$date": "2017-12-28T21:07:02.143Z"
            }
        }
    ],
    "allowComments": true,
    "status": "public",
    "__v": 1
}

my Schema 我的架构



        const mongoose = require('mongoose')
        const Schema = mongoose.Schema;

        //Create Schema
        const StorySchema = new Schema({
        title: {
            type: String,
            required: true
        },
        body: {
            type: String,
            required: true
        },
        status: {
            type: String,
            default: 'public'
        },
        allowComments: {
            type: Boolean,
            default: true
        },
        comments: [{
            commentBody: {
                type: String,
                required: true
            },
            commentDate: {
                type: Date,
                default: Date.now
            },
            commentUser: {
                type: Schema.Types.ObjectId,
                ref: 'users'
            }
        }],
        user: {
            type: Schema.Types.ObjectId,
            ref: 'users'
        },
        date: {
            type: Date,
            default: Date.now
        }
    });

        mongoose.model('stories',StorySchema, 'stories');

And my JS file ,my post method works exactly how I wish but delete doesn't work at all (Cannot read property 'comments' of undefined) 和我的JS文件,我的post方法完全按我的意愿工作,但删除根本不起作用(无法读取未定义的属性“ comments”)



    router.post('/comment/:id' , (req , res) => {
    Story.findOne({
        _id: req.params.id
    })
    .then(story => {
        const newComment = {
            commentBody: req.body.commentBody,
            commentUser: req.user.id
        }

        //Push to comments array
        story.comments.unshift(newComment);

        story.save()
        .then(story => {
            res.redirect(`/stories/show/${story.id}`)
        })
    });
    })

    router.delete('/comment/:id', (req, res) => {
    Story.remove({
        _id: req.body.id.comments
    })
    .then(() => {
        req.flash('success_msg', 'Comments Removed!');
        res.redirect('/dashboard');
    })
    });

here is my handlebars file with form 这是我的带有表单的把手文件

{{#each story.comments}}

<form action="/stories/comment/{{id}}?_method=DELETE" method="post" id="delete-form">
<input type="hidden" name="_method" value="DELETE">
<button type="submit" class="btn red"><i class="fa fa-remove"></i> Delete</button>
</form>

{{/each}}

The error I got 我得到的错误

TypeError: Cannot read property 'comments' of undefined
at router.delete (/Users/ar2z/Desktop/fierce-caverns-70427/routes/stories.js:197:20)

Help me please. 请帮帮我。 I'm completely lost. 我完全迷路了。

I actually encountered the same error recently. 我最近实际上遇到了相同的错误。 I have found you need to do this: 我发现您需要这样做:

router.delete("/comments/:id", function(req,res){
   var Model = require("myModel");
   //Run a find and update query to delete the comment
   Model.findOne({_id:req.params.id}, function(err,doc){
      if(doc && !err){
         doc.comments = doc.comments.filter(function(comment){
            //This will filter out the comment you want to delete
            return comment._id != req.body.commentId
         })
      }
      res.redirect("/comments/")
   })
}

My fault was from the beginning when I was trying work with array element the same way as i'm working with Mongo object 我的错是从一开始就以与使用Mongo对象相同的方式尝试使用数组元素



    Story.remove({
            _id: req.body.id.comments
        })

Code above is not working for array element it's working with object but for delete element from array I use: 上面的代码不适用于数组元素,它适用于对象,但适用于我从数组中删除元素:



Story.update( { }, { $pull: { comments: { _id: req.params.id }}}, { multi: true } )

This code Remove Items from an Array of Documents 这段代码从一系列文档中删除项目

$pull MongoDb documentation $ pull MongoDb文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM