Transferring information between different collections in MongoDB using Mongoose can lead to encountering a VersionError

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."

Answer №1

It's quite peculiar how I stumbled upon a workaround that seems to do the trick without fully comprehending its workings:

Here's the unconventional solution: create a new variable that mirrors the original object exactly and then feed it into TakenClassesModel.

const duplicateClass = {
  _id: classTaken._id,
  rating: classTaken.rating,
  title: classTaken.title,
};

const clonedClass = TakenClassesModel(duplicateClass);
await clonedClass.save();

The reasoning behind this method eludes me, but for now, it appears to be the only effective way to address the issue at hand.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reset input field when checkbox is deselected in React

How can I bind value={this.state.grade} to clear the input text when the checkbox is unchecked? The issue is that I am unable to modify the input field. If I were to use defaultValue, how would I go about clearing the input box? http://jsbin.com/lukewahud ...

Conceal form upon submission with jQuery

Is it possible to have a html form inside a table and then hide it once the form is submitted? The Form: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <tr> <td colspan="3"> <h ...

Unveil SQL Limit with a Simple Scroll Load

After successfully laying out and creating my website, the next step is to load more results on scroll. This question has been posed numerous times before, but I am curious if there is a simple solution that can seamlessly integrate into my current setup. ...

Difficulty implementing clickable dropdown buttons in a React navbar

After some tweaking, I was able to create buttons that trigger dropdown menus which disappear when clicked off. However, a problem arises when any button is clicked - all of the dropdowns appear at once. It appears that setting the state for one button a ...

An insightful guide on effectively binding form controls in Angular using reactive forms, exploring the nuances of formControlName and ngModel

Here is the code snippet: list.component.html <form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()"> <div nz-row *ngFor="let remark of checklist> <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" styl ...

Transfer the array using Ajax to a PHP script

I have an array generated using the .push function that contains a large amount of data. What is the most effective way to send this data to a PHP script? dataString = ??? ; // Is it an array? $.ajax({ type: "POST", url: "script.php" ...

Exploration of jsTree capabilities

I am currently exploring the jsTree plugin API and I'm struggling to grasp where exactly the API functions like set_theme, show_dots, etc. should be applied. On this page, I noticed that some functions are preceded by jQuery, while others are precede ...

Creating a legitimate svg element using javascript

While working with SVG, I had an issue where I added a <rect> element directly into the svg using html, and then created a new element (without namespace) <circle> with javascript. However, the <circle> element did not display in the svg ...

Incorporating a lasting element into the _app.js file of Next.js

I am currently experimenting with my first Nextjs app and encountering difficulties when trying to incorporate a persistent sidebar. While looking for solutions, I came across Adam Wathan's article on persistent layouts in Nextjs. However, it appears ...

choosing a database upon establishing a connection with mongodb

My goal is to execute a command on mongodb from a shell script. Previously, I was able to do this using the following commands prior to Mongodb version 2.6: mongo --host db.example.com/mydb -u myuser -pMyPassword --eval 'db.getSiblingDB("mydb").addUs ...

`Increase Your Javascript Heap Memory Allocation in Next.js`

We are facing a challenge with the development environment for our Next.js application. Issue The Javascript heap memory is consistently depleting. Here are the specific error logs: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out ...

How can custom CSS and JS be loaded in Sencha Touch based on the user's device - PC, tablet, or smartphone?

Is there a way to configure a webpage so that when the user is accessing it from a PC (using Safari/Chrome/Firefox), they see the "normal" version of the page, but if they are using an iPad to view the same URL, they get Sencha Touch (css, js) files in t ...

What is the best way to eliminate the final character from a series of repeated Xs and following strings

Data consists of [one][two][three]. I want to exclude the last set of brackets and have a result like [one][two]. How can this be achieved using jQuery? ...

Switching from constructors to Hooks in REACT

I am currently working on adding a modal example within a function in my project. I have a specific requirement to incorporate hooks instead of using the constructor in a class-based component. This is the code snippet with the class-based implementation: ...

The functionality of the AngularJS nested router is not functioning properly

I am encountering some challenges with Angular routing, specifically when using nested routes: The current 'abc' state works flawlessly for the route /admin/team/:teamId .state('admin', { url: '/admin', controller: & ...

Google is currently unable to provide the accurate latitude and longitude of the current position

I'm looking to incorporate geolocation functionality into my Laravel project. I've implemented this code, but it seems to be giving me slightly different latitude and longitude values. function getLocation() { var x = document.getElementById( ...

Passing data between Vue.js components effortlessly without relying on events

At the moment, I am utilizing Laravel Nova. It's worth noting that it operates using vue.js. I've created a personalized vue component which requires the ability to modify data inside another component. This specific component is located in the ...

The export "hasInjectionContext" is not provided by the source file "node_modules/vue-demi/lib/index.mjs", but it is being requested in the file "node_modules/pinia/dist/pinia.mjs"

Every time I launch my program, the console displays an error message stating that "hasInjectionContext" is not exported by "node_modules/vue-demi/lib/index.mjs", imported by "node_modules/pinia/dist/pinia.mjs" at line 6:9. I ...

Switch the background image of a link within an accordion with a simple click

I'm attempting to create a toggle effect for a background image on a links within an FAQ accordion using javascript. After referencing this jsfiddle example (http://jsfiddle.net/QwELf/), I was able to get things to function. You can view my page in ...

Using httpRequest to handle binary data in JavaScript

Having trouble deciphering the response of an http request that is a binary datastream representing a jpeg image, despite numerous attempts. Edit: Including the full code snippet below: xmlhttp = false; /*@cc_on@*/ /*@if (@_jscript_versio ...