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

103
Views
Mongoose element in array of objects

i would like to update and element in array of objects if it is already in the array.

For now what i'm doing is this :

exports.pushDocumentsList = (req, res) => {
  const documents = [];

  documents.push({
    _id: req.body.document._id,
    fileid: req.body.document.fileid,
    filename: req.body.document.filename,
    url: req.body.document.url ? req.body.document.url : '',
    status: req.body.document.status ? req.body.document.status : '',
    expiredate: req.body.document.expiredate
      ? req.body.document.expiredate
      : '',
  });

  User.findOneAndUpdate(
    {
      _id: req.profile._id,
    },
    { $push: { documents } },
    { new: true, useFindAndModify: false },
    (err, docu) => {
      console.log(docu);
      if (err) {
        return res.status(400).json({
          error: "Non è stato possibile aggiornare i documenti dell'utente",
        });
      }
      return res.status(200).json({
        status: 'success',
        message: 'Documento caricato con successo',
        doc: req.body.document,
      });
    }
  );
};

So this only appends the element to the array , i would like to know how can i update the element if it's already in the array.

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

0

you can do it with. notation and $eleMatch example with dot:

const user = await User.findOneAndUpdate(
  { _id: req.profile._id, "documents._id": "someId" },
  {
    $set: {
      "documents.$.filename": "file changed"
      "documents.$.status": "status will change",
    },
  }, //update
  { new: true } //options
);
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!