首页 > 解决方案 > 使用 remove() 删除数组元素不起作用?

问题描述

我在我的 API 中使用以下代码从数组中删除元素

deleteCommentLike: async(req, res) => {
        const { error } = createComLikeValidation(req.body);

        if (!error) {
            const { user_id, comment_id } = req.body;

            //   const likeModel = new likeSchemaModel({user_id: user_id, post_id: post_id});
            await commentlikeSchemaModel
                .find({ user_id: user_id, comment_id: comment_id })
                .remove();
            let commenttData = await commentSchemaModel.findById(comment_id);
            console.log(commenttData.usersLiked);

            commenttData.likes = --commenttData.likes;
            commenttData.usersLiked.remove(user_id);
            await commenttData.save();

            res.status(200).json({ error: false, data: "done" });
        } else {
            let detail = error.details[0].message;
            res.send({ error: true, data: detail });
        }
    },

在这里,这一行不起作用:commenttData.usersLiked.remove(user_id);. 它没有给出任何错误,但user_id没有从我的数据库中删除。

"use strict";
const mongoose = require('mongoose');
const Joi = require('joi');

var commentSchema = mongoose.Schema({
    //other data
    usersLiked: [{
        type: mongoose.Types.ObjectId,
        default: []
    }],
    //other data
}
var commentSchemaModel = mongoose.model('comments', commentSchema);
module.exports = {
    commentSchemaModel,
}

在我的 mongodb 中,它看起来像下面

在此处输入图像描述

我已经尝试过使用它,commenttData.usersLiked.remove(mongoose.Types.ObjectId('user_id')); 但结果是一样的。

这可能是什么原因,我如何从数组中删除值?

标签: javascriptnode.jsarraysmongodbmongoose

解决方案


您应该使用更新操作:

commenttData.update({_id: mongoose.Types.ObjectId("5f099..")}, {$set: {usersLiked: yourUpdatedUsersLikedArray}})

当您触发编译器忽略的 js noop时,您期望的 remove() 错误丢失了。

Mongoose 并没有按照你使用它的方式实现属性更新操作。


推荐阅读