javascript - 删除运算符在 Javascript 中不起作用

标签 javascript json node.js mongoose ecmascript-6

这是一个在 JSON 对象返回给客户端之前删除敏感信息的函数。传递到函数中的数据可以是 JSON 对象或 JSON 对象数组。为什么这个功能不起作用?

我知道这个问题还有其他解决方案,但这让我的大脑很烦。

我已经在此函数中记录了大量信息,尽管 JavaScript 是异步的,但函数仍按其应有的顺序运行 - 递归在最终 return 语句被命中之前完成。

现在的问题是,即使一切似乎都正常,并且 delete 运算符返回 true,但当函数最终返回时,被删除的属性仍然存在。

从 MongoDB 获取的数据示例:

[
    {
        'id': '1',
        'name': 'John',
        'password': 'test123',
        'emailAddress': 'john@example.com',
        'emailAddressVerificationCode': 'A897D'
    },
    {
        'id': '2',
        'name': 'Andrew',
        'password': 'test123',
        'emailAddress': 'andrew@example.com',
        'emailAddressVerificationCode': '90H8D'
    },
    {
        'id': '3',
        'name': 'Matthew',
        'password': 'test123',
        'emailAddress': 'matthew@example.com',
        'emailAddressVerificationCode': '56C7C'
    }
]

如有任何想法,我们将不胜感激。

UserService.cleanJSON = (data) => {

    if (Array.isArray(data)) {
        for (let i = 0; i < data.length; i++){
            data[i] = UserService.cleanJSON(data[i]);
        }
    } else {

        if (data.password) delete data.password;
        if (data.emailAddressVerficationCode) delete data.emailAddressVerficationCode;
        if (data.mobileNumberVerificationCode) delete data.mobileNumberVerificationCode;
        if (data.accountType) delete data.accountType;
    }


    return data;
};

最佳答案

您可能正在使用 Mongoose 或任何其他 ODM,对吗? 如果是这样,您必须知道除非调用方法 .lean() ( http://mongoosejs.com/docs/api.html#query_Query-lean ),否则无法更改结果。

Mongoose 可以保护模型免受任何修改,除非您分离结果。

关于javascript - 删除运算符在 Javascript 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41815816/

相关文章:

python - Circleci 与 gcloud sdk UnicodeDecodeError

javascript - Lodash拒绝获取返回对象

javascript - AWS S3 Javascript SDK 重新发送请求失败

javascript - Javascript 异步回调背后的机制

javascript - [ foo : 'bar' ] 是什么类型的 JS 对象

java - 从 MongoDB Java 中的数组中删除文档

javascript - 是否可以在其他 then for() 循环中使用 await ?

javascript - 如何创建 Howerjs 进度条?

javascript - Sequelize - 如何仅返回数据库结果的 JSON 对象?

java - 使用 Jackson 打印 json 数组