Error: A surprise 'dot' token was found while defining the function

As part of my API development, I'm working on creating a register route. However, I encountered an issue when trying to utilize the User.function - AddUser method from my model file. The error message mentions an unexpected token .. Below is the code snippet:

router.post('/register', (req, res, next) => {
    let newUser = new User({
        username: req.body.username,
        name: req.body.name,
        email: req.body.email,
        password: req.body.password,
        photoUrl: req.body.photoUrl
    })

    User.addUser(newUser, (err, user) => {
        if (err) {
            res.send('Failed');
        } else {
            res.send('Registered');
        }
    });
});

For reference, here is the relevant section from the model file:

const mongoose = require('mongoose');
const schema = mongoose.Schema;
const bcryptjs = require('bcryptjs');

const userSchema = new schema({
    username: { type: String, required: true },
    name: { type: String },
    email: { type: String, required: true },
    password: { type: String, required: true },
    photoUrl: { type: String }
});

const User = module.exports = mongoose.model('User', userSchema, 'users');

module.exports.addUser(newUser, callback) => {
    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

Answer №1

To implement the addUser function in your model file, include the following code snippet:

module.exports.addUser = (newUser, callback) => {
    bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
            if (err) throw err;
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

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

I'm working on an Angular2 project and I'm looking for a way to concatenate all my JavaScript files that were created from TypeScript in Gulp and then include them in my index

How can I concatenate all JavaScript files generated from typescript in my Angular2 project with Gulp, and then add them to my index.html file? I am using Angular2, typescript, and gulp, but currently, I am not concatenating the javascript files it genera ...

Several features - Second function malfunctioning

The initial inquiry is effective. However, the subsequent one is encountering issues as it is failing to confirm if an email contains the "@" symbol. My attempted solution involved reordering the functions related to email validation. <body onload="ch ...

Having trouble with solving the issue of not being able to overwrite the compiled `User` model

Encountered this error message: OverwriteModelError: Cannot overwrite User model once compiled. at backend/models/userModel.js:34:23 Here is the code snippet for authmiddleware: import jwt from "jsonwebtoken"; import asyncHandler from "expr ...

Enhancing w3-import-html with JavaScript

<div id="import" includeHTML="page.html"></div> function getInclude() { var x = document.getElementById("import").includeHTML; //returns 'undefined' alert(x); } function modInclude() { document.getElementById("import") ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

Tips on using jQuery to horizontally align an element in the viewport

Although this question has been raised before, my situation is rather unique. I am currently constructing an iframe for future integration into a slideshow component on the website. The challenge lies in the fact that I have a dynamically sized flexbox th ...

Instructions on obtaining a distinct daily array from the weather API array that provides a detailed 5-day weather report every 3 hours

Seeking assistance with my weather app development on React using axios with the openweathermap.org API. Currently stuck on getting data formatted in a specific way from the 5-day forecast it provides, totaling 40 reports over the 5 days. The API response ...

Utilize JavaScript to include HTTP headers in image requests

In my JS/HTML5 Project with angularjs, I have implemented protection for my API by setting an authorization token in the HTTP header. Now, I am also looking to secure access to images stored on the server. While I know how to accomplish this on the server ...

Breaking Down URLs with JavaScript

I am looking to extract specific portions of a URL and here is my progress so far. <script type='text/javascript'> var query = window.location.pathname.split( '/' ); query = window.location.pathname.split( '.html' ); v ...

Building a versatile and interactive table using AngularJS with data sourced from a

I am currently working on creating a dynamic table using Angular JS to display data received from a Spring Rest Service. Here is the code snippet I have been working with: // JavaScript Document var app = angular.module("SDLC", []); app.config([&apos ...

Debouncing in AngularJS with $watch

In my code, I have an HTML search field represented by the following: <input ng-model-options="{ debounce: 500 }" type="text" ng-model="name"> Along with the JavaScript snippet: $scope.$watch('name', function(newVal, oldVal) { ...

EJS forEach method not displaying output

Trying to work with this .ejs file that's supposed to loop through an object and retrieve data from an API. However, after fetching the data, it appears that nothing is being displayed on the screen. I've checked the API results in the console l ...

Hover shows no response

I'm having trouble with my hover effect. I want an element to only be visible when hovered over, but it's not working as expected. I've considered replacing the i tag with an a, and have also tried using both display: none and display: bloc ...

The error message "prettyPrint is not defined" indicates that the function prettyPrint

I am facing an issue with ReferenceError: prettyPrint is not defined. Can you provide some help? <a class="question helpcenterheading" href="http://www.google.com">How do I reach out to you?</a> <span class="answer">Just a moment...</ ...

Scroll to the top of a new page with Material UI's table component

Feeling a little stuck here. I've tested various settings with scrollTop, but haven't had much luck. To clarify, I'm working with Material UI and their pagination features in conjunction with a table (you can find the documentation here). W ...

What is the best way to trigger dependent APIs when a button is clicked in a React Query application

On button click, I need to call 2 APIs where the second query depends on the result of the first query. I want to pass data from the first query to the second query and believe using "react-query" will reduce code and provide necessary states like "isFetch ...

Tips for sending formData (file upload) via jQuery ajax with MVC model

My Web Development Challenge : //IMAGE UPLOAD var formData = new FormData(); var totalImages = document.getElementById("ImageUpload").files.length; for (var x = 0; x < totalImages; x++) { ...

The promise of a MongoDB connection with Node.js returns as 'awaiting fulfillment'

Greetings to all! A few weeks ago, I embarked on the journey of learning javascript, node.js and mongo. As a beginner, I have an interesting task at hand today. My goal is to add a simple document to the mongoDB and perform a conditional check. So here&apo ...

Webpack failing to load jQuery correctly

In the process of transitioning my application.js application into smaller page bundles using SplitChunks, I have encountered a situation in my users/show.html.erb page where I am utilizing the following tag to import the specific chunk. <%= javascript ...

Error Alert: LocalStorage is undefined in this context - NextJS

Having trouble retrieving access and refresh tokens from local storage. Each attempt results in a 500: Internal Server Error, with an error indicating LocalStorage is undefined. Research suggests that LocalStorage may not be compatible with rendering with ...