簡體   English   中英

如何從Mongo中的數組中刪除元素

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

我完全陷於Mongoose和刪除方法。 我有一個帶有注釋的頁面和帶有“ 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方法完全按我的意願工作,但刪除根本不起作用(無法讀取未定義的屬性“ 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');
    })
    });

這是我的帶有表單的把手文件

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

我得到的錯誤

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

請幫幫我。 我完全迷路了。

我最近實際上遇到了相同的錯誤。 我發現您需要這樣做:

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

我的錯是從一開始就以與使用Mongo對象相同的方式嘗試使用數組元素



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

上面的代碼不適用於數組元素,它適用於對象,但適用於我從數組中刪除元素:



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

這段代碼從一系列文檔中刪除項目

$ pull MongoDb文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM