I want to return all users in JSON format except their passwords. To do so, I have done something like this
try {
const rawResults = await model.find(querry).limit(limit).skip(startIndex)
results.results = rawResults.forEach((v) => delete v.password)
} catch (error) {
results.error = error
}
now when I am trying to console.log the result value, it always returns
{ next: null, results: undefined }
Please help me fix this issue. Thank you so much.
CodePudding user response:
Array.prototype.forEach
returns undefined
.
Just call rawResults.forEach((v) => delete v.password)
without the results.results =
and your code will work.
CodePudding user response:
forEach modifies the original object.
If you don't need rawResults any more (hopefully, as passwords should be encrypted as Nick pointed out), you can use your code as follows:
try {
const rawResults = await model.find(querry).limit(limit).skip(startIndex)
rawResults.forEach((v) => delete v.password)
results.results = rawResults
} catch (error) {
results.error = error
}
If you need separate RawResults and result objects you can use map instead of forEach:
try {
const rawResults = await model.find(querry).limit(limit).skip(startIndex)
results.results = rawResults.map(({password, ...v}) => v)
} catch (error) {
results.error = error
}