【问题标题】:How to remove an element from an array within Mongo如何从 Mongo 中的数组中删除元素
【发布时间】:2017-12-30 00:12:49
【问题描述】:

我完全被Mongoose 和删除方法所困扰。 我有一个带有 cmets 的页面和带有按钮 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
}

我的架构



        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');

我的 JS 文件,我的 post 方法完全按照我的意愿工作,但 delete 根本不起作用(无法读取未定义的属性 'cmets')



    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');
    })
    });

这是我的车把文件,格式为

{{#each story.cmets}}

<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}}

我得到的错误

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

请帮帮我。我完全迷路了。

【问题讨论】:

  • 请显示您发送的请求。该错误提示您的请求正文没有“id”对象

标签: javascript mongodb express post mongoose


【解决方案1】:

我最近实际上遇到了同样的错误。我发现你需要这样做:

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/")
   })
}

【讨论】:

  • 非常感谢您的帮助,不幸的是它对我不起作用,顺便问一下“doc”在这里是什么意思?
  • 据我了解,doc 是通过findOne 方法找到的文档。然后你可以访问它的字段,修改它们,最后保存更改的副本。
  • 非常感谢安迪,我明白了
【解决方案2】:

我的错误从一开始就在我尝试使用数组元素时,就像我使用 Mongo 对象一样



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

上面的代码不适用于与对象一起使用的数组元素,而是用于从我使用的数组中删除元素:



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

此代码从文档数组中删除项目

$pull MongoDb documentation

【讨论】:

    猜你喜欢
    • 2013-01-26
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2019-04-09
    • 2013-09-01
    相关资源
    最近更新 更多