[英]Delete object from array using map
I have an API call to get all the users of my application.我有一个 API 电话来获取我的应用程序的所有用户。 I have a problem, that the getAll method returns each users's password encrypted.我有一个问题,getAll 方法返回每个用户的加密密码。 I don't want to return the password.我不想返回密码。
That's my method:那是我的方法:
async getAll(pagination) {
try {
const { UserAdmin: userAdminSchema } = this.getSchemas();
let usersAdmins = await userAdminSchema.paginate({}, {
sort: { created: 'desc' },
limit: pagination.limit ? parseInt(pagination.limit) : 10,
page: pagination.page ? parseInt(pagination.page) + 1 : 1,
});
if (!usersAdmins) {
throw new errors.NotFound('No UserAdmins found.');
}
usersAdmins.docs.map(async (u) => {
delete u.password;
});
return usersAdmins
} catch (error) {
throw error;
}
{
"docs": [
{
"roles": [
"Admin",
"Read",
"Modify",
],
"_id": "5ffecc12a687a30580239a10",
"name": "john",
"email": "john@gmail.com",
"password": "$2a$10$K6oKiiWKsIWmAGgkG7TmH.WjVpraNg45Uc0nber3FnF26oEzdgTS2",
"created": "2021-01-13T10:31:46.982Z",
"__v": 0
},
{
"roles": [
"Read"
],
"_id": "5ffea1f1dd60b80718af6e3b",
"name": "Megan",
"email": "megan@gmail.com",
"password": "$2a$10$V8ARIjxhEHCC1COcvtQEmOZ3IfXm5oiANdLmyHyipy1GmWSD3ctWK",
"created": "2021-01-13T07:32:01.665Z",
"__v": 0
},
],
"totalDocs": 2,
"limit": 10,
"totalPages": 1,
"page": 1,
"pagingCounter": 1,
"hasPrevPage": false,
"hasNextPage": false,
"prevPage": 1,
"nextPage": null
}
I just want to the delete the password.我只想删除密码。 How I can achieve this?我怎样才能做到这一点? The map I have done, still returns the password:我做的map,还是返回密码:
usersAdmins.docs.map(async (u) => {
delete u.password;
});
I suspect the objects in your array are immutable, which is why your code didn't work.¹我怀疑您数组中的对象是不可变的,这就是您的代码不起作用的原因。¹
Instead, create and return a new object, and use the array that map
returns:相反,创建并返回一个新的 object,并使用map
返回的数组:
return {
...usersAdmins,
docs: usersAdmins.docs.map(
u => Object.fromEntries(Object.entries(u).filter(([key]) => key !== "password"))
)
};
Live Example:现场示例:
const usersAdmins = { "docs": [ { "roles": [ "Admin", "Read", "Modify", ], "_id": "5ffecc12a687a30580239a10", "name": "john", "email": "john@gmail.com", "password": "$2a$10$K6oKiiWKsIWmAGgkG7TmH.WjVpraNg45Uc0nber3FnF26oEzdgTS2", "created": "2021-01-13T10:31:46.982Z", "__v": 0 }, { "roles": [ "Read" ], "_id": "5ffea1f1dd60b80718af6e3b", "name": "Megan", "email": "megan@gmail.com", "password": "$2a$10$V8ARIjxhEHCC1COcvtQEmOZ3IfXm5oiANdLmyHyipy1GmWSD3ctWK", "created": "2021-01-13T07:32:01.665Z", "__v": 0 }, ], "totalDocs": 2, "limit": 10, "totalPages": 1, "page": 1, "pagingCounter": 1, "hasPrevPage": false, "hasNextPage": false, "prevPage": 1, "nextPage": null }; const result = {...usersAdmins, docs: usersAdmins.docs.map( u => Object.fromEntries(Object.entries(u).filter(([key]) => key;== "password")) ) }. console;log(result);
¹ Re your original code: ¹ 重新您的原始代码:
async
is pointless, none of the code in your callback is using await
(nor does it need to) async
是没有意义的,回调中的代码都没有使用await
(也不需要)map
but not using the array it creates is an anti-pattern.使用map
但不使用它创建的数组是一种反模式。 If you don't need the result array, use forEach
or a for-of
loop or just a for
loop.如果不需要结果数组,请使用forEach
或for-of
循环或仅使用for
循环。 (But here I suspect we do need to use the array that map
produces.) (但在这里我怀疑我们确实需要使用map
生成的数组。)If you are using Mongoose lib for model User, declare the password field like this would solve your problem.如果您为 model 用户使用 Mongoose lib,声明密码字段可以解决您的问题。
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please add a name']
},
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
match: [
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
'Please add a valid email'
]
},
role: {
type: String,
enum: ['user', 'publisher'],
default: 'user'
},
password: {
type: String,
required: [true, 'Please add a password'],
minlength: 6,
select: false // <=== IMPORTANT
}
});
It means that password would not be returned whenever you get Users.这意味着无论何时获得用户,都不会返回密码。
you can create a new object in map and return that, or set the password to the empty string with Object.assign您可以在 map 中创建一个新的 object 并返回它,或者使用 Object.assign 将密码设置为空字符串
const data = [{ "roles": [ "Admin", "Read", "Modify", ], "_id": "5ffecc12a687a30580239a10", "name": "john", "email": "john@gmail.com", "password": "$2a$10$K6oKiiWKsIWmAGgkG7TmH.WjVpraNg45Uc0nber3FnF26oEzdgTS2", "created": "2021-01-13T10:31:46.982Z", "__v": 0 }, { "roles": [ "Read" ], "_id": "5ffea1f1dd60b80718af6e3b", "name": "Megan", "email": "megan@gmail.com", "password": "$2a$10$V8ARIjxhEHCC1COcvtQEmOZ3IfXm5oiANdLmyHyipy1GmWSD3ctWK", "created": "2021-01-13T07:32:01.665Z", "__v": 0 }, ]; const dataWithOutPassword = data.map((user) => { return { roles: user.roles, _id: user._id, name: user.name, email: user.email, created: user.created } }); console.log(dataWithOutPassword); const dataWithOutPassword2 = data.map((user) => { return Object.assign({}, user, { password: '' }) }); console.log(dataWithOutPassword2)
in paginate function you can select every fields that you need with select
property, like following code:在分页 function 中,您可以使用select
属性 select 您需要的每个字段,如以下代码:
await userAdminSchema.paginate({}, {
select: "name email",
sort: { created: 'desc' },
limit: pagination.limit ? parseInt(pagination.limit) : 10,
page: pagination.page ? parseInt(pagination.page) + 1 : 1,
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.