I was trying to sort an array of user objects coming back from the database base on their age, but something really strange happened.
The following code isn't working:
async function getAllUsers(){
let _users = await User.find({});
//error here, it shows that cannot read age of null, but why is
//stats undefined? I thought the async/await already resolved the promise?
let sorted = _users.sort((a, b) => b.stat.age - a.stat.age)
return sorted;
}
Here is the working code after a bunch of researches, but I am not exactly sure why this is working
async function getAllUsers(){
let _users = await User.find({});
let deepclone = JSON.parse(JSON.stringify(_users))
let sorted = deepclone.sort((a, b) => b.stat.age - a.stat.age)
return sorted;
}
I understand that I am creating a brand new object off of _users
so that the deepclone
loses reference to the _users
array object, but how does this help solving the problem?
//=======just to be clear=======//
let _users = await User.find({})
console.log(_users)
/* this logs
{
_id: 65a4d132asd,
stat: { age: 24 }
}
*/
//without doing JSON.parse & JSON.stringify
_users.sort((a,b) => {
console.log(a)//this logs ---> {_id: 65a4d132asd,stat: { age: 24 }}
console.log(a.stat)//this logs ---> undefined
})
//with JSON.parse & JSON.stringify
let deepclone = JSON.parse(JSON.stringify(_users))
deepclone.sort((a, b) => {
console.log(a)//this logs ---> {_id: 65a4d132asd,stat: { age: 24 }}
console.log(a.stat)//this logs ---> 24
})