[英]Delete operator not working in Javascript
This is a function that removes sensitive information from a JSON object before it gets returned to the client. 这是一个在返回到客户端之前从JSON对象中删除敏感信息的函数。 The data that's being passed into the function would either be a JSON object or an array of JSON objects.
传递给函数的数据可以是JSON对象,也可以是JSON对象数组。 Why would this function not work?
为什么这个功能不起作用?
I know that there are other solutions to the problem, but this is annoying my brain. 我知道这个问题有其他解决办法,但这让我大脑烦恼。
I have logged plenty of information in this function and even though JavaScript is asynchronous the functions are running in the order that they should - the recursion is finishing before the final return statement is hit. 我已在此函数中记录了大量信息,即使JavaScript是异步的,函数也按它们应该的顺序运行 - 递归在命中最终return语句之前完成。
The issue right now is that even though everything seems to be working and the delete
operator is returning true
, the attributes being deleted are still present when the function finally returns. 现在的问题是,即使一切似乎都在工作并且
delete
运算符返回true
,但当函数最终返回时,仍然存在被删除的属性。
Example data
which is being fetched from MongoDB: 从MongoDB获取的示例
data
:
[
{
'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'
}
]
Any thoughts would be appreciated. 任何想法将不胜感激。
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;
};
You are probably using Mongoose or any other ODM, right? 您可能正在使用Mongoose或任何其他ODM,对吧? If so, you have to know that you can not change the results unless you call the method
.lean()
( http://mongoosejs.com/docs/api.html#query_Query-lean ). 如果是这样,您必须知道除非调用方法
.lean()
( http://mongoosejs.com/docs/api.html#query_Query-lean ),否则无法更改结果。
Mongoose keeps the model safe from any modifications unless you detach the result. 除非您分离结果,否则Mongoose可以保证模型不受任何修改。
删除JSON中最后一个花括号后面的逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.