Help me please. Working with Mongoose, and I want to check if there are duplicates in the "ViolationID" field and delete them, except the last one created. I think, _id: { $lt: record._id } works incorrect. May be some types of _id or record._id not matched. I’m confused, because documents in collection not deleting.
Violation.find({}, { "ViolationID": 1 })
.sort({ _id: 1 })
.then((violations) => {
violations.forEach(function (record) {
Violation.deleteMany({
_id: { $lt: record._id },
"ViolationID": record["ViolationID"],
});
});
});
Below documents that cannot be deleted
{
_id": "649adc629b36c9ee95228d96",
"ViolationID": 98,
},
{
"_id": "649add653629f115a960d498",
"ViolationID": 98
}
I tried this Remove duplicate documents based on field
and other threads, these cases don’t work for me
2
Answers
So, adding .then or .catch after deleteMany() help it to work. This behavior is not clear to me. Do you know why this is happening?
I don’t see the reason why it does not work. Anyway, may approach would be this one: