I'm facing an issue where Mongoose is unable to find a matching document with the id when transferring data from one collection to another.
On my website, users search for classes in a Mongo DB collection called "classes." Once they find a class successfully, it should be copied to a collection named "classes_taken." However, I encountered the following error:
VersionError: No matching document found for id "64779936f186a42f6b09658b" version 0 modifiedPaths "_id, has_final, description, offered_fall, offered_spring, meets_with_subjects, instructors, joint_subjects, total_units, related_subjects, hass_attribute, pdf_option, is_half_class, level, url, subject_id, title, lab_units, design_units, public, offered_summer, lecture_units, preparation_units, is_variable_units, offered_IAP"
at generateVersionError (/Users/nayeemurrahman/Documents/Projects/extinguisher/server/node_modules/mongoose/lib/model.js:461:10)
at model.save (/Users/nayeemurrahman/Documents/Projects/extinguisher/server/node_modules/mongoose/lib/model.js:518:28)
at /Users/nayeemurrahman/Documents/Projects/extinguisher/server/index.js:44:20
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
version: 0,
modifiedPaths: [
'_id', 'has_final',
'description', 'offered_fall',
'offered_spring', 'meets_with_subjects',
'instructors', 'joint_subjects',
'total_units', 'related_subjects',
'hass_attribute', 'pdf_option',
'is_half_class', 'level',
'url', 'subject_id',
'title', 'lab_units',
'design_units', 'public',
'offered_summer', 'lecture_units',
'preparation_units', 'is_variable_units',
'offered_IAP'
]
This is the code snippet causing the issue:
// POST request to add a class taken
app.post("/addClass", async (req, res) => {
// assuming a string was sent in the request body
// retrieve the class from the database based on the given subject_id
// add that class to the classes_taken database
const subject_id = req.body.subject_id;
const classTaken = await ClassModel.findOne({
subject_id: subject_id,
});
try {
const newClass = TakenClassesModel(classTaken);
// THE ERROR OCCURS IN THE LINE BELOW
await newClass.save();
} catch (err) {
console.log(err);
}
res.json(classTaken);
});
How can I solve this issue? The version is not important to me; I just want to transfer all data from "classes" to "classes_taken."