I encountered a strange issue while working on an Express API. I need to retrieve a list of posts from the MongoDB database and then add a new property to each post object before returning it to the client.
Despite my efforts, I am not able to successfully add the newProperty
as intended. The list of objects retrieved from the database remains in their original state without the additional newProperty
attached to them.
What could be causing this problem?
Here is the code snippet:
exports.fetchPosts = async (userID) => {
// Fetch posts of user's friends and the user himself
try {
// Get friend's posts
const friends = await User.findById(userID).select('friends');
const allPosts = [];
for (let i = 0; i < friends.friends.length; i++) { // For each friend
// Retrieve each friend's posts
const posts = await Post.find({ author: friends.friends[i] }).populate('author', 'username');
posts.forEach(friendPost => {
friendPost.newProperty = 'newProperty';
allPosts.push(friendPost);
});
} catch(err){ console.log(err)}
}