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

154
Views
MongoDB : mongoose findbyidandupdate condition not working

I want to update an array in a document where array is array of user object.

The problem is i don't want to add duplicates in this array ( not the same user more than one time).

what i do :

const updatedTopic = await Topic.findByIdAndUpdate(
    // @ts-ignore
    { _id: id, 'votes.user': { $ne: req.user?._id.valueOf() } },
    // @ts-ignore
    { $push: { votes: { year, comment, user: req.user } } },
    { new: true }
  );

But this isn't working as you can see below :

  {
  "name": "Argomento 1",
  "exam": {
    "$oid": "62b71b9dcaf3e92ac568c729"
  },
  "slug": "argomento-1",
  "user": {
    "$oid": "62534e5798a11bcba35464f6"
  },
  "votes": [
    {
      "year": 2022,
      "comment": "",
      "user": {
        "$oid": "62b22fd314c40b9067f84cc2"  -> same user
      },
      "_id": {
        "$oid": "62b8bbcf876b2d27570fdf86"
      }
    },
    {
      "year": 2022,
      "comment": "",
      "user": {
        "$oid": "62b22fd314c40b9067f84cc2"  -> same user
      },
      "_id": {
        "$oid": "62b8bbd5876b2d27570fdf89"
      }
    }
  ],
  "createdAt": {
    "$date": {
      "$numberLong": "1656168790097"
    }
  },
  "updatedAt": {
    "$date": {
      "$numberLong": "1656274729989"
    }
  },
  "__v": 0
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I don't know why but changing findByIdAndUpdate to findOneAndUpdate works fine.

Probably findByIdAndUpdate checks only the id condition.

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!