Executing the constructor-defined method following the retrieval of a document from the database

UPDATE (AN ALTERNATIVE SOLUTION)

Upon further exploration, I discovered that what I needed was the ability to make the method static so that it could be applied independently from the class.


Let's consider the following constructor:

export const User = class User {
  constructor(
    email,
    password,
    name,
  ) {
    this.name = name;
    this.email = email;
    this.password = password;        
  }

  async save() {
    const db = getDb("messages");
    const result = await db.collection("users").insertOne(this);
    return {
      ...result.ops[0],
      _id: result.ops[0]._id.toString(),
    };
  }

  newMethod (_id) {
    //Perform actions using User
  }
};

When fetching the User through a CRUD operation (e.g., findOne), I receive an object back that doesn't allow me to use the newMethod defined in the constructor. It appears that the query result is read-only and does not inherit the constructor's methods. How can this issue be resolved?

Answer №1

Upon explicitly returning a plain object:

return {
  ...result.ops[0],
  _id: result.ops[0]._id.toString(),
};

The said object remains disconnected from the User instance on which you invoked the save method.

If you intend to retain the information from result within the User instance, you should assign it to properties on this. (This would eliminate the necessity of the _id parameter in newMethod as well.)

As an example, to directly duplicate all own, enumerable properties from result.ops[0] onto this, you could employ Object.assign:

async save() {
    const db = getDb("messages");
    const result = await db.collection("users").insertOne(this);
    Object.assign(this, result.ops[0]);         // Retains _id unaltered
    this._id = result.ops[0]._id.toString();    // Converts _id into a string if desired
}

Subsequently, you can access this._id within newMethod.

(Alternatively, you have the option of assigning specific properties.)

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

Using AngularJS to use ng-show, sg-hide, and ng-click

Is there a way to create a Start button that hides when clicked and shows a Stop button instead? When the Stop button is clicked, the Start button should reappear. I've attempted this but it doesn't seem to work. Any suggestions or ideas? &a ...

Using dates as the X axis in Chart.js can be achieved even when there is no corresponding Y axis value

My goal is to ensure that the chart always displays a value on the final X axis, I am unable to use "distribution: 'series'" as it causes the chart to go out of scale, Guessing the correct value to set for "time: {min / max}" in order to exceed ...

The modelErrors property in the json response has not been defined

Currently, I am attempting to parse a JSON response. The JSON response is being received in the responseText property. Initially, I receive the response from JSON structured as shown below: {"Success":false,"Error":true,"ErrorType":1,"ModelErrors":{"Name" ...

Testing React components using the React Testing Library

I've been working on creating a test unit for my React Application using React Testing Library, but I've hit a roadblock. I've gone through all the documentation but I'm still stuck. The API was set up using create React app. One of th ...

Traversing an object and assigning its properties as values in another object using JavaScript

I need to create an object using an array as keys and another object with default properties as values. I am unsure of how to loop through and assign the key/value pairs to the new object. Can you help me out? Thank you! The object myFinalObj is initially ...

After selecting a subitem, the side menu will automatically close

I designed a side menu that expands to reveal submenus. However, when I click on a subitem within a submenu, the entire list closes. The HTML, CSS, and JavaScript code all appear to be correct as the template is functioning properly. But as soon as I ins ...

"An error occurred stating that currDateEnd.setHours is not a valid function

I am attempting to transform my date into ISO format and adjust the hours to 23. Below is my code: var currDateEnd = $('#calendar').fullCalendar('getView').start; console.log(currDateEnd); currDateEnd.toDate().toISOString(); console.lo ...

AngularJS tips for resolving an issue when trying to add duplicates of a string to an array

Currently dealing with a bug that occurs when attempting to push the same string into an array that has already been added. The app becomes stuck and prevents the addition of another string. How can I prevent the repeat from causing the app to get stuck w ...

The initial execution of the getDocs function may encounter some difficulties

Whenever a user connects from localhost:3000/ (which automatically redirects to /profile), I try to fetch all documents from Firebase. However, it does not work on the first attempt. Strangely, upon refreshing the page, it successfully retrieves the docume ...

md-input container displays content only upon user interaction

Currently, I am working with AngularJs 1 and Angular-Material Design. One issue I encountered was with a md-input container used for file uploading. The problem I faced was that even after selecting a file, it wasn't being displayed in the md-input co ...

Incorporate the variables specified in the parent PHP file into the PHP code being received through

I am currently working on a project that involves enabling a user to view his profile upon login. However, I am aiming to have the dashboard load all other profile pages through ajax, such as the view profile and edit profile pages. My progress so far inc ...

Executing Multiple setTimeout jQuery in a Class: A Comprehensive Guide

Is there a way to hide elements with the class .content and the attribute .data-time using the setTimeout() function in jQuery? Here is the HTML code: <div class="content first" data-time="200"> </div> <div class="content second" data-time ...

Is there a Node template engine similar to EJS that seamlessly integrates with HTML templates?

Is there a template engine for NodeJS similar to EJS that doesn't alter the original HTML template structure with its use of parentheses? In EJS, one might utilize the following code snippet to embed specific data into the HTML template: <script& ...

Is there a way to remove a checkbox node that has already been generated?

I've been working on creating a to-do list, and I've run into an issue with deleting the checkbox once the task is complete. I attempted to create a function within the main function containing an if/else statement, but it didn't seem to wo ...

"Upon refreshing, the background image reverts back to its original default setting

With React, I have implemented a feature where users can navigate to their 'settings' page and select an image to set as their background. I used DOM manipulation to achieve this functionality successfully! However, whenever the page is refreshed ...

Searching for mongodb records using intersecting criteria

My database structure is designed to keep track of two values that increase throughout the day, organized by days. The structure of my documents looks like this: { year: number, month: number, day: number, valueA: number, valueB: number, } This ...

Encountering an Error with Polymer 1.0 and Django: Unresolved Reference to KeyframeEffect

I've been experimenting with Polymer 1.0 in combination with django and snapdragon. Although I've managed to render the elements successfully, I've hit a roadblock when it comes to animations. The code I'm using is almost identical to t ...

The serverless functions in Next.Js only seem to work after being pinged

I am dealing with an endpoint in my project that receives messages from a WhatsApp webhook. This endpoint then makes an asynchronous call to another endpoint and responds with a 200 status back to the WhatsApp webhook. While this process works smoothly an ...

Get a single object from an array with .single method provided by @ngrx

Seeking to retrieve an Observable containing a single object from an array of objects in my store. I aim to utilize the .single operator, which should throw an exception if there is not exactly 1 object present. However, I'm struggling with this as my ...

Animate jQuery Images - Transform and smoothly reveal element

Hey there! I've managed to create a color switcher that gives a sneak peek of different themes. Currently, it simply switches the image source and loads the new image. But I'm curious if it's possible to add a fadeIn effect to enhance the t ...