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

241
Views
Why does the updateOne doesn't validate according to the schema model, even after setting the runValidators to true?

Okay, so I am trying to update an array of objects in MongoDB. I have used updateOne in this case to update the array of objects.

Here is an example of an array of objects in JSON format which my app sends

[
    {
      "_id": 6,
      "todo": "walk"
    },
    {
        "_id":7,
        "todo":"run"
    },{
        "_id":8,
        "todo":"dance"
    }
]

Here is my schema

const todos = new mongoose.Schema(
  {
    todos_list: [
      {
        _id: {
          type: Number,
          required: true,
          unique: true,
        },
        todo: { type: String, required: true, minlength: 1, maxlength: 100 },
      },
    ],
    user_id: { type: String, required: true },
  },
  { collection: "user.todosList" }
);

Here is the code for finding the document on the basis of user_id and updating it.

const { token, todos_list } = req.body;
  try {
    const userData = verifyToken(token);
    const user_id = userData.id;

    const query = await todoSchema.updateOne(
      { user_id },
      { $addToSet: { todos_list } },
      { runValidators: true }
    );
    res.send({ status: "ok", query });
  } catch (err) {
    res.send({ status: "error", err });
  }

When I run this code for the first time, it runs perfectly. But the problem comes when I update my todo value to something else.

For example, let's say that I want to update my todo at id:7. Right now the current value of my current todo is run. And if I change it to run at 5 p.m.. What the code will do is add another object at the end of my todo_list array. The runValidators are of no use and doesn't check for the duplicate _id in my document.

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!