Home > OS >  Appending a property to each object in an array of objects
Appending a property to each object in an array of objects

Time:12-15

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?

CodePudding user response:

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)
     })
}

CodePudding user response:

Editing the single element objects won't update the element in the parent array.

You could create a separate array and add the objects with the new property in it:

router.get('/admin/manage_accounts/view_all', (req,res) => {
    Community_Member.find({}, (error, community_member) => {
        const result = [];
        community_member.forEach(function(element){
            result.push({
                ...element,
                Role: "Community Member"
            })
        })
        
        console.log(result)
        res.send(result)
     })
}
  • Related