User authentication using .pre save process

I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object.

For example, a user object could contain:

{
  "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d79687e794d79687e79236e6260">[email protected]</a>",
  "username" : "testing",
  "name" : "Test User"
}

or it might not include the name field:

{
  "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="522637212612263721267c313d3f">[email protected]</a>",
  "username" : "testing"
}

In cases where the name field is present, I want to ensure it has at least 6 characters.

I'm attempting to implement this validation process within my model using the .pre method, but I'm encountering unexpected results.

var UserSchema = new Schema({
  id                      : String,
  name                    : String,
  email                   : String,
  username                : String
},{ timestamps: { createdAt: 'created_at',updatedAt: 'updated_at' } });

UserSchema.pre('save', function(next) {
  console.log(this); //no evidence of name property here

  if("name" in this){
    console.log("Name found"); //this is always the output
  } else {
    console.log("Name not found");
  }
  next();
});

The provided code snippet serves for testing purposes. However, even with the given JSON objects, the output consistently shows "Name found," despite the absence of the name property when checking the console. Could this behavior be influenced by the presence of the name property in the model?

Answer №1

Upon inspecting the user object in the console, you may notice that the property name is missing. This could be due to the fact that the provided JSON data does not contain a field for the name attribute. In order to handle this scenario, you can apply your logic or conditions based on the presence of the name property as shown below:

UserSchema.pre('save', function(next) {
  if (this.name !== undefined) {
    if (this.name.length <= 6) {
      // Handle error appropriately
    }
  }
  next();
});

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

Tips for managing the mongo client in NodeJS

Exploring the concept of managing the mongo client in a node application has led me to consider creating a new client for each collection retrieval. Here is an example implementation: const getCollection = (collectionName) => { return MongoClient.connec ...

Is there a way to display a PHP error message while submitting the form asynchronously?

Utilizing phpMailer in combination with AJAX to send emails. The objective is to send the email and then showcase any error messages from submit.php on contact.php Currently, every submission displays "Message sent" even if it was not actually sent. Con ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

Obtaining the latest record ID from MySQL using node.js

I am currently working on a project where I need to add new user information to a MySQL database. I'm looking for a way to retrieve the ID of the most recently added record so that I can create login details for the user. The environment in which this ...

What is the methodology behind incorporating enumerations in typescript?

I've been curious about how typescript compiles an enumeration into JavaScript code. To explore this, I decided to create the following example: enum Numbers { ONE, TWO, THREE } Upon compilation, it transformed into this: "use strict ...

Performing a Javascript validation to ensure that a value falls within

How can I check if an input number falls within a specified range? I need to display if it is within the range, higher, or lower than the acceptable range. My current Javascript code seems to be causing an error message stating it is an invalid entry. It ...

Using JavaScript to create a search bar: Can "no results found" only show after the user has completed typing their search query?

How can I ensure that the "no match" message only appears after the user has finished typing in their search query, rather than seeing it while they are still typing "De" and the list displays "Demi"? usernameInput.addEventListener("keyup",function(){ ...

creating a JSON object in PHP that can be easily parsed by JavaScript

In my project, I have an extensive list of items, each item further divided into four sub-items. While it's convenient for me to organize this data in nested arrays using PHP, I encounter issues when trying to transfer them as a JSON object to the cli ...

Select multiple options by checking checkboxes in each row using React

Is it possible to display multiple select checkboxes with more than one per row? For example, I have four options [a, b, c, d]. How can I arrange it to have 2 options per row, totaling 2 rows instead of having 1 option per row for 4 rows? ☑a ☑b ☑c ...

What is the best way to incorporate CSS into JavaScript code?

Here is the code I am working with: <script type = "text/javascript"> function pic1() { document.getElementById("img").src = "../images/images/1.png"; } function pic2() { document.getEl ...

Can JavaScript be used to dynamically assign events to elements on a webpage?

I am currently using the following code: if ( $.support.touch == true ) { $(window).on('orientationchange', function(event){ if ( full == false ) { self.hideAllPanels("7"); } }); } else { $(window).on(&apo ...

Is there a jQuery function that can produce repeated output and append content with each successive click?

Attempting to implement a dynamic searchbar with various parameters has led me to explore using jQuery to load and clone the searchbar file in order to append it to the body dynamically. I have made several attempts to modify selectors without achieving t ...

Network-wide posting of Mongoose Schema

I am faced with a situation where I have two Node.js applications both utilizing Mongoose, but on separate machines. The first machine hosts a MongoDB database which the second machine connects to in order to add documents at certain intervals. What I am c ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

Tips for identifying MIME type errors in an Angular 9 application and receiving alerts

While working on my Angular app, I encountered the MIME type error Failed to load module script: The server responded with a non-javascript mime type of text/html. Fortunately, I was able to resolve it. Now, I'm stuck trying to figure out how to rece ...

Ways to enhance an image by zooming in when the user reaches a designated area on the webpage

I have implemented a feature where an image zooms in to letter L when the user scrolls on the page. However, I want this zoom effect to occur only when the user reaches a specific section of the site, rather than immediately when the image loads. In my exa ...

Each Vue instance on the page has its own isolated Vuex store

I have a situation where I am creating multiple Vue apps on the same page: import Vue from "vue"; import App from "./App.vue"; import useStore from "./store"; const arr = [1, 2]; for (const index of arr) { const store = use ...

Is there a way for me to choose all the classNames that conclude with a specific word within the MUI sx property?

I am currently working with MUI and I have a need to modify certain properties that are prefixed with random IDs. How can I target, for instance, the first one using: '& endsWith(MuiAccordionDetails-root)' I wish to achieve this because the ...

Sending javascript data to php within a modal popup

I am currently working on passing a javascript variable to php within a modal window, all while remaining on the same page (edit.php). Although I plan to tackle handling this across separate pages later on, for now, I have successfully implemented the foll ...

I am encountering an error when attempting to import the app from the server.js file in Express

In my server.js file, I have set up an express server and exported the app from it. //server.js require("dotenv").config(); const express = require("express"); const app = express(); const connectToDb = require("./connectToDb ...