【问题标题】:remove array element with remove() is not working?使用 remove() 删除数组元素不起作用?
【发布时间】:2020-11-01 21:05:03
【问题描述】:

我在我的 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')); 但结果是一样的。

这可能是什么原因,我怎样才能从数组中删除值?

【问题讨论】:

    标签: javascript node.js arrays mongodb mongoose


    【解决方案1】:

    您应该使用update 操作:

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

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

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

    【讨论】:

    • 因为可以有更多喜欢的用户`yourUpdatedUsersLikedArray`不能手动定义我想从数组中删除给定的元素
    • 嗯,你确定吗?
    猜你喜欢
    • 2013-02-02
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    相关资源
    最近更新 更多