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

134
Visualizações
Mongoose - Update and return updated subdocument

I have two schemas:

Org

const schemaOrg= new Schema({
  name: String,
  atts: [schemaAtt],
});

and Att

const schemaAtt = new Schema(
  {
    isActive: Boolean,
    name: String,
    description: String,
    color: String,
    icon: String,
  }
);

If I try to update Atts of an Org document

const updateAtt = async (parent, { input }) => {
  const attId = input.id;
  const orgId = input.orgId;
  const res= await modelOrg.findOneAndUpdate(
    { _id: orgId, 'atts._id': attId },
    {$set:{'atts.$':input}},
    {
      returnDocument: 'after',
      projection: { _id: 0, atts: 1 },
    }
  );
  return res.atts;
};

with the following input:

{
  "input": {
    "id":"61799ab734465282d39a6570",
     "organizationId":"615ca4d39a35776c189c1324",
    "isActive": true,
    "description": "AC des11",
    "icon":"wrench"
      }
}

this is the result:

{
        "id": "6179bd08c35a27df069bd2f4",
        "name": null,
        "isActive": true,
        "description": "AC des11",
        "color": null,
        "icon": "wrench"
      }

First of all, the ID is changed!!! and whatever I did not send changed to null (color)

mongoose debug shows the following command runs

orgs.findOneAndUpdate({ _id: new ObjectId("615ca4d39a35776c189c1324"), 'atts._id': new ObjectId("61799ab734465282d39a6570")}, { '$set': { 'atts.$': { isActive: true, description: 'AC des11', icon: 'wrench', _id: new ObjectId("6179bd08c35a27df069bd2f4"), name: [] } }}, { returnDocument: 'after', upsert: false, remove: false, projection: { _id: 0, atts: 1 }, returnOriginal: false})

I have 2 questions:

  1. how can I fix it? If I run
{
      'atts.$.isActive': input.isActive,
      'atts.$.name': input.name,
      'atts.$.description': input.description,
       'atts.$.color': input.color,
       'atts.$.icon': input.icon,
  },

instead of {$set:{'atts.$':input}}, Then the update is working. How can I just pass the input instead of fields one by one?

  1. I want to project only the "att" that "was found and updated" (to be returned). now it returns all of atts on Org

Thanks in advance.

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