我正在尝试fetch
共同的朋友,并将他们置于共同朋友的财产中。
但是,在res.send()
函数的users对象中,它不包含共同的朋友属性
router.get('/friends', auth, async (req, res) => {
try {
let users = await User.find({
friends: req.user._id
})
users.map((user) => {
let userAltered = {
...user.toObject()
}
userAltered.userImage = userAltered.userImageThumbnail;
delete userAltered.userImageThumbnail;
userAltered.mutualFriends = [];
userAltered.friends.forEach((friend) => {
if (req.user.friends.findIndex((myFriend) => {
return friend.toString() == myFriend.toString()
}) > 0) {
userAltered.mutualFriends.push(friend);
}
})
return userAltered;
})
res.send({
users,
loggedInUserId: req.user.id
});
} catch (e) {
res.status(500).send(e);
}
})
答案 0 :(得分:0)
查询返回的users
对象将处于不可变状态。您需要先将其转换为javascript对象。当前,只有users
内的对象被转换为对象,由于users
列表本身是不可变的,因此更改将不会应用于它。
对于您而言,您需要先执行此操作
const result = users.map(u => u.toObject());
router.get("/friends", auth, async (req, res) => {
try {
let users = await User.find({
friends: req.user._id,
});
const result = users.map((u) => u.toObject());
result.map((user) => {
user.userImage = user.userImageThumbnail;
delete user.userImageThumbnail;
user.mutualFriends = [];
user.friends.forEach((friend) => {
if (
req.user.friends.findIndex((myFriend) => {
return friend.toString() == myFriend.toString();
}) > 0
) {
user.mutualFriends.push(friend);
}
});
return user;
});
res.send({
result, // returning result object
loggedInUserId: req.user.id,
});
} catch (e) {
res.status(500).send(e);
}
});