Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Appending a property to each object in an array of objects

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)
     })
}
about 4 years ago · Juan Pablo Isaza Report

0

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)
     })
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!