<分区>
我试图根据年龄对从数据库返回的一组用户对象进行排序,但发生了一些非常奇怪的事情。
以下代码无效:
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;
}
这是经过大量研究后的工作代码,但我不确定为什么会这样
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;
}
我知道我正在从 _users
创建一个全新的对象,这样 deepclone
就失去了对 _users
数组对象的引用,但是这对解决问题有何帮助?
//=======只是说清楚=======//
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
})