Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda