Encountering validation error while testing serverless API offline and sending post request data to MongoDB using Postman

While conducting backend testing of my serverless API using Postman, the data I'm sending is triggering the error message

Users validation failed: email: Path email is required., name: Path name is required., password: Path password is required.

User Model

const userSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      trim: true,
      required: true,
      unique: true,
      validate(value){
        if(!validator.isEmail(value)){
          throw new Error ("Please enter correct email");
        }
      }
    },
    name: {
      type: String,
      trim: true,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
    salt: String,
    role: {
      type: String,
      default: "Normal",
    },
    created: {
      type: "Date",
      default: Date.now,
    },
    subscription: {
      type: String,
      default: "dev",
    },
    token: {
      type: String,
      default: "free",
    },
  { collection: "Users" }
);

userSchema.post("save", function (_doc, next) {
  _doc.password = undefined;
  return next();
});

User Handler

/* Create User*/
module.exports.create = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  Database.connectToDatabase()
    .then(() => {
      let body = querystring.decode(event.body);
      console.log(event.body)
      const randomKey = uuidv4();
      let newUser = new User({
        name: body.name,
        email: body.email,
        password: body.password,
        apiKey: randomKey.replace(/-/g, ""),
      });
    //console.log("TESTING")  
      newUser.save(function (err, user) {
        if (err) {
          callback(null, {
            statusCode: err.statusCode || 500,
            headers: { "Content-Type": "text/plain" },
            body: err.message,
          });
        } else {
          callback(null, {
            statusCode: 200,
            body: JSON.stringify(user),
          });
        }
      });
    })
    .catch((err) => {
      callback(null, {
        statusCode: err.statusCode || 500,
        headers: { "Content-Type": "text/plain" },
        body: err.message,
      });
    });
};

Data Being Sent through Postman

curl --location --request POST 'http://localhost:3000/prod/users' \
--header 'Content-type: application/json' \
--data-raw '{"name": "hello", "password": "pass", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e584968183a5849683cb868a88">[email protected]</a>"}'

Expected Outcome

The intent behind sending this data should result in the creation of a new user and API key, storing them in MongoDB. As I'm not utilizing an express server for this process, it's possible that the data isn't being routed correctly. If this is indeed the case, what adjustments or additions do I need to make in order to successfully create a user via Postman?

Answer №1

When sending the information, I needed to format it into key-value pairs in x-www-form-urlencoded

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

utilizing a Bootstrap modal element throughout multiple HTML documents

I have a bootstrap modal dialog div that I want to use in all 4 html pages of my web application without repeating the code. I have a common JavaScript file for this purpose. What is the best way to achieve this? <!-- Modal --> <div class="modal ...

Attempting to create a pattern of illuminated tiles on a webpage

Similar Question: Making tiles on a web page light up different colours in a sequence I am currently attempting to illuminate specific tiles within a 4x4 grid on a webpage. The grid has been set up, but the designated tiles do not light up as intende ...

Tips for handling promise coverage within functions during unit testing with Jest

How can I ensure coverage for the resolve and reject functions of a promise within a function while conducting unit tests using Jest? You can refer to the code snippet below. Service.js export const userLogin = data => { return AjaxService.post( ...

Converting flat data into a nested object using JavaScript

Exploring the realms of react/ES6, I encountered an intriguing anomaly while utilizing the reduce method to convert a flat array received from an API into a nested object structure. Although I was well-versed in map and filter functions, the concept of red ...

Obtaining the most up-to-date information using unique column value - utilizing mongoid and rails4

Within my MongoDB database, I have a collection called kevent that has entries structured like so: _id, user_id action created_at 43gy5235rwedwe 11 logout 2014-05-30 04:01:32 +0000 563gy5wwwedwex 11 ...

Getting EdgesHelper to align properly with Mesh in Three.js

Within a dynamic scene, multiple mesh objects (specifically cubes) have been included. A unique EdgeHelper has been generated for each cube to track its movements and rotations. Whenever a particular cube mesh is selected, I am aiming to alter the color o ...

In Firefox version 3.6, sIFR 3 is displaying text in a random arrangement along a single line

For some reason, sIFR 3 is behaving oddly in Firefox. In other browsers like IE, Chrome, and Safari, the Flash element within a 412px wide box remains consistent at that width. However, in Firefox, it initially stretches to the width of the Body element b ...

When referencing an object in AngularJS that is defined within the $scope, it is important to

Imagine having a NameController implemented in AngularJS. You can define variables like so: this.name = 'Joe'; Alternatively, you could use: $scope.name = 'Joe'; I have a preference for accessing all variables using object notation: ...

Intercepting HTTP requests on specific routes with Angular 4+ using an HTTP Interceptor

I've developed an HTTP_INTERCEPTOR that needs to function on certain routes while excluding others. Initially, it was included in the main app module file. However, after removing it from there and adding it to specific modules, the interceptor conti ...

Getting rid of website end values in the phrase ""." and "。""

I am in the process of creating a JavaScript regex that will identify string values without any special characters that may interfere with URLs. While I have successfully matched the . character, I have learned that the 。 character can also act as a ful ...

What caused the discord.js mongoose query to fail?

Hello everyone, I am trying to retrieve data from a database and display it as a bot reply. However, I am encountering an error. Here is the schema: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const profileSchema = new ...

Avoid Conversion of HTML Entities in Table Cells

<table> <tr> <td>&gt;</td> </tr> <tr> <td>&&#xfeff;GT</td> </tr> </table> In the code snippet above, I have table cells containing HTML entities. A re ...

Record the cumulative amount computed using an asynchronous callback

If I use code similar to the one below, I am able to obtain the total byte size value every time a file is added. How can I log out only the total files size after it has been calculated in the fs.stat callback? var fs = require('fs'); var to ...

Is it better to use e.target instead of refs when testing?

I have been frequently creating components like this: <input ref="ckbx" type="checkbox" checked={this.props.checked} onChange={() => this.props.onChange(this.refs.ckbx.checked)} /> However, I recently realized that testing this is ...

The iframe content is not updating despite using jQuery

On this site , the following code is present: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <iframe style="position: absolute; top: 0; left: 0; height: 100%; width: 100%" src="blank.html"></iframe ...

How to Trigger an ascx.cs Function from an ascx Page with JavaScript

I'm currently working with a code behind file that includes a method: public string ProductsAsJson() This method is responsible for returning a JSON representation of multiple products. In order to integrate some Angular functions into my ascx page, ...

When attempting to implement orbit controls with Three.js, an error occurred stating "GET http://127.0.0.1:3000/build/three.module.js net::ERR_ABORTED 404 (Not Found)"

In my attempt to construct a Sky Box using three.js, I successfully created the cube and applied textures. However, I am now faced with the task of incorporating camera controls. After creating the OrbitControls.js file and implementing the necessary code, ...

Eliminate any values that have not been chosen from the dropdown array in ngx-select-dropdown

Scenario: The challenge involves managing selected values in Angular applications using the ngx-select-dropdown. Users can select multiple values, which are then sorted into "buckets" and sent to the API. Problem: I'm facing difficulty removing a sel ...

Is the ASP.NET Validator a trustworthy tool?

Utilizing the ASP.NET Validator to validate numerous inputs in my WebForm has proven effective on the client side. I appreciate being able to validate inputs without triggering a page reload. However, when attempting to use the Validator on the code behin ...

Navigating a complex web: Djikstra algorithm applied to a multigraph

Encountering an issue while implementing Dijkstra's algorithm on a multigraph. The graph consists of nodes representing stops with information and connections to other stops (edges). However, the challenge arises when there are multiple bus options be ...