Embed a method within a class

My colleague's code that I need to integrate into my website is structured in a class and asynchronous style for the database. While I personally don't see the necessity for this approach, I have found that it is not harmful:

const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
class User {
    constructor() {
        this.user = mongoose.model('user', {
            email: String,
            password: String,
            hash: String,
            salt: String,
        })
    }

    checkEmailPassword(email, password) {
        return new Promise((resolve, reject) => {
            this.user.find({email, password}, {}, (err, users) => {
                if(err) throw(err)
                if(users.length > 0) resolve(users[0])
                else reject('not found')
            })
        })
    }

    addAccountWOCheck(userInf, way) {
        return new Promise((resolve, reject) => {
            var collection = new this.user(userInf)
            // collection.setPassword(userInf.password)
            collection.save((err, data) => {
                if (err) throw (err)
                else resolve(data)
            })
        })
    }
}

My next challenge is to create a setPassword function that will encrypt the user's password. I want this function to be called by a user instance rather than the class itself, but I'm unsure of how to implement this within the existing class:

setPassword = function(email) {
    var salt = crypto.randomBytes(16).toString('hex');
    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'SHA1').toString('hex');
}

If anyone has any insights or guidance on this matter, I would greatly appreciate it.

Edit 1:

I made an attempt to include the setPassword function within the class:

setPassword(collection) {
    collection.hash = "abc";
    console.log("setPassword: " + JSON.stringify(collection));
}

and then called it within the addAccountWOCheck method:

var collection = new this.user(userInf)
this.setPassword(collection)
collection.save((err, data) => {
    if (err) throw (err)
    else resolve(data)
})

While I can see that setPassword is being called, the collection is not being modified in the database as expected.

Answer №1

If you're searching for information on prototypes, this article provides a comprehensive guide on how to enhance the functionality of an existing object.

Take a look at this example for better understanding:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
};

Understanding JavaScript Prototypes

In JavaScript, all objects inherit properties and methods from their prototype.

Objects created using an object literal or new Object() inherit from Object.prototype.

Objects created with new Date() inherit Date.prototype.

Object.prototype sits at the top of the prototype chain.

All JavaScript objects (Date, Array, RegExp, Function, etc.) inherit from Object.prototype.

Answer №2

My Edit 1 is functioning correctly

Include the following function within the class:

setPassword(collection) {
    collection.hash = "abc";
    console.log("setPassword: " + JSON.stringify(collection));
}

Then invoke it in addAccountWOCheck:

var collection = new this.user(userInf)
this.setPassword(collection)
collection.save((err, data) => {
    if (err) throw (err)
    else resolve(data)
})

The reason why the hash of collection was not updating successfully before is because I neglected to add the hash field in the user schema (unlike what I originally posted in OP).

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

What is the best way to save data from an ng-repeat array in MEANJS?

I've been exploring MEANJS at meanjs.org and I'm having trouble storing array data for ng-repeat in the deal object, which includes dealtype and dealprice. Despite setting up addFields for the ng-repeat input tag in the create form, the data isn& ...

Is it possible to utilize Jquery in order to add an opening <tr> tag and a closing </tr> tag within a dynamic table?

I have been experimenting with the code snippet below in an attempt to dynamically add a closing </tr> tag followed by an opening tag after every three cells, essentially creating a new row. Progress has been made as the DOM inspector shows a TR nod ...

Revamp the Twitter button parameters or alter its settings

I'm working on a web page that includes a Twitter button. Before the button, there is an input field and a form where users can easily add relevant hashtags for the page. The goal is to take the text from the input field and populate it in the Twitter ...

Invoke a method in a separate class

I am facing issues with passing variables to another file. I have checked my code multiple times but cannot find a solution. It keeps giving me an error in the function. onclick="limit();javascript:AyudaTipos(2)"/> The function is: function limit ( ...

Creating a straightforward image slideshow using jQuery featuring next and previous buttons

I am looking for assistance in adding next and previous buttons to this slider. I came across a code snippet on a blog that could be useful, which can be found at .net/dk5sy93d/ ...

Retrieving the headers from an ajax request

Is there a method to retrieve the complete request headers used in an AJAX call made through jQuery? ...

Toggle sidebar: expand/collapse

Looking for some assistance with my website project. I currently have two arrows to open and close the sidebar, but I would like one button to handle both actions instead. Can someone help me edit my code snippet to achieve this? Keep in mind that I am new ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...

When using Magento, pasting the same link into the browser produces a different outcome than clicking on window.location - specifically when trying to add items to the

I'm in the process of setting up a Magento category page that allows users to add configurable products directly from the category page, which is not the standard operation for Magento. After putting in a lot of effort, I have almost completed the ta ...

Deleting a button from a list item or array in Angular 12

Having some trouble removing a list item with the click button, I've tried a few options but nothing seems to be working. Can anyone offer assistance? I need to remove a list item from my users array when clicked. Below is the Typescript code and cor ...

No response data being displayed after Angular post request

After sending a POST request via Postman, I received the expected response with a status of 400. However, when I tried sending the same request using Angular's http.post in the browser, I only received a 400 error without any response data. https://i ...

Variable in v-for loop is not properly declared

Currently, I am attempting to iterate through an array of objects retrieved from the backend and display these objects on the frontend. The Vue framework is throwing an error stating that "event" is not defined on the instance but referenced during render. ...

Why is my console showing a SyntaxError with JSON.parse and an unexpected character?

I am facing an issue. When I attempt to call a PHP page for some data with specific requested parameters using AJAX asynchronous call, I encounter the following error: SyntaxError: JSON.parse: unexpected character var jsonData = $.ajax({ u ...

Ways to send data to nested elements when implementing secure routes?

I am currently working on a project to develop a 'Train Ticket Reservation System' using ReactJS. In order to access the services, users must login, so I have implemented protected routes to render certain components. Instead of relying on the de ...

React frontend communicating without backend server

Is it possible to send a message between two frontend users on web applications built with React? ...

Extracting JSON data from a string using jQuery

http://localhost/project1/index.php //AJAX region $(function(){ $.ajax({ type : 'GET', url : 'https://jsonplaceholder.typicode.com/posts/1', success : function(data){ console.log('success \n', data); }, error ...

A single integer variable that is shared across all sessions in node.js

Is there a way to create an integer variable that is shared among all client sessions in node.js and can be accessed in client HTML? I need this variable to be displayed in the HTML page and have the ability to update it within the page, with the new val ...

Including a cancel button to close the open window

var messagebox = Ext.widget("messagebox", { target: grid, progressMessage: "Loading" }); The message box displayed above indicates the loading progress bar that appears when the download button is clicked. I am looking to incorporate a cancel button i ...

What is the best way to change data into an array using Java script?

In this code snippet, I am utilizing a loop to send data to an ajax function in JSON format: foreach($careers->getItems() as $item){ if($item->getDepartment()==$departmentID && $item->getLocation()==$location ...

Steps to set up Feathers instance in Jest environment once

When running Jest tests, I want to utilize only one instance of feathers "app" throughout. This is how I currently import app in each test: const app = require('../../src/app'); describe(`service`, () => { it('registered the service&ap ...