2

I'm using Node.js and Mongoose to access a MongoDB database and return an array of objects from a MongoDB collection. However, I want to append a property to each of the returned objects. My code is shown below

router.get('/admin/manage_accounts/view_all', (req,res) => {
    Community_Member.find({}, (error, community_member) => {
        community_member.forEach(function(element){
            element.Role = "Community Member"
        })
        
        console.log(community_member)
        res.send(community_member)
     })
}

The objects from the database are returned, but the Role property is not appended to any of the objects and I'm not certain why. Can anyone give me a bit of insight?

2
  • Do you have the same issue with element["Role"] = "Community Member"? Commented Dec 15, 2021 at 6:50
  • Yes, unfortunately I do. Commented Dec 15, 2021 at 23:40

1 Answer 1

1

The standard functional way to do it is by using map

router.get('/admin/manage_accounts/view_all', (req,res) => {
    Community_Member.find({}, (error, community_member) => {
        community_member = community_member.map(element => {
            element.Role = "Community Member"
            return element
        })
        
        console.log(community_member)
        res.send(community_member)
     })
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response. Unfortunately, this does not produce the desired output. The Role property still isn't appended to each object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.