Mongoose从Schema arr中删除对象

时间:2017-08-17 10:10:46

标签: node.js mongodb mongoose

您好我正在尝试使用Mongoose从我的模型中删除一个数组,它似乎不起作用。我想从 collectionImages 中删除一个对象。这是我的代码:

架构

var CollectionSchema = mongoose.Schema({
    collectionName: String,
    collectionImages: [
        {
            imageName: String,
        }
    ],
    path: String
});

删除方法:

router.delete("/collection/:id/:imageId", function (req, res) {
    var imageId = req.params.imageId;

    Collections.findById(req.params.id, function (err, collections) {
        if (err) {
            console.log(err);
        } else {

            for (var i = 0; i < collections.collectionImages.length; i++) {
                if (collections.collectionImages[i]._id == imageId) {
                    var checkedImageId = collections.collectionImages[i]._id;
                     collections.collectionImages[i].splice(imageId,1);
                };
            }

        }
        ;
    });
});

表格:

 <form id="deleteForm" action="/collection/<%= collections._id %>/<%= image._id %>?_method=DELETE" method="post">
                    <button class="fa fa-minus-circle">Delete</button>
                </form>

1 个答案:

答案 0 :(得分:1)

尝试以下

Collections.update(
   { _id: req.params.id },
   { $pull: { 'collectionImages': { '_id': req.params.imageId } } }
).exec(function (err, user) {
    if (err) { res.status(500).send(err); return; }
    res.send();
});

更多阅读this