'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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
