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

136
Views
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
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!