Tips for incorporating a User ID object into an Ajax request

Currently, I am delving into the world of web development and tackling a client-server project that involves allowing users to authenticate themselves and store their blood pressure readings. While the authentication part is functioning properly, I am encountering difficulties when it comes to storing a blood pressure reading. Despite successfully verifying all features using curl, I am facing errors from the server whenever I attempt to create a blood pressure reading. The root of my issue seems to lie in my inability to include the User ID as an object in the Ajax call. Any assistance on this matter would be greatly appreciated.

Below, you will find the curl script that is currently working:

API="http://localhost:4741"
URL_PATH="/readings"

curl "${API}${URL_PATH}" \
  --include \
  --request POST \
  --header "Content-Type: application/json" \
  --header "Authorization: Bearer ${TOKEN}" \
  --data '{
    "reading": {
      "systolic": "'"${S}"'",
      "diastolic": "'"`${D}`"'',
      "pulse": "'"${P}"'"
    }
  }'

echo

Here is the schema delineating the structure for the blood pressure reading:

const mongoose = require('mongoose')

const readingSchema = new mongoose.Schema({
  systolic: {
    type: Number,
    required: true
  },
  diastolic: {
    type: Number,
    required: true
  },
  pulse: {
    type: Number,
    required: true
  },
  owner: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  }
}, {
  timestamps: true
})

module.exports = mongoose.model('Reading', readingSchema)

The following code snippet represents the blood pressure reading route that has been set up within the server app:

// CREATE
// POST /readings
router.post('/readings', requireToken, (req, res, next) => {
  // set owner of new reading to be current user
  req.body.reading.owner = req.user.id

  Reading.create(req.body.reading)
    .then(reading => {
      res.status(201).json({ reading: reading.toObject() })
    })
    .catch(next)
})

Additionally, here is the Ajax call made to the API:

// Create a reading
const readingCreate = function (data) {
  let dataToSend = [{ user: store.user._id }, { data }]
    dataToSend = JSON.stringify({ dataToSend })
  return $.ajax({
    method: 'POST',
    url: config.apiUrl + '/readings',
    data: dataToSend,
    headers: {
      ContentType: 'application/json',
      Authorization: 'Bearer ' + store.user.token
     }
  })
}

The Chrome Dev tools provide insight into the communication between the frontend and backend:

Request URL: http://localhost:4741/readings Request Method: POST Status Code: 500 Internal Server Error Remote Address: [::1]:4741 Referrer Policy: strict-origin-when-cross-origin

This is what the server console reports:

20:47:52 GMT-0600 (Central Standard Time): TypeError: Cannot set property 'owner' of undefined at router.post (/Users/Ken/sei/projects/project2/bp_tracker/app/routes/reading_routes.js:62:26)

Answer №1

When you send an array with the user ID, make sure to assign the value of req.body.user to reading.owner rather than using req.user.id for some reason.

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

Navigating and extracting nested JSON properties using JavaScript (React)

I am currently working with a nested JSON file that is being fetched through an API. The structure of the JSON file looks something like this: { "trees":{ "name":"a", "age":"9", "h ...

What is the most effective way for server.js to send a request to a controller?

When I need to send data from a controller to my main server.js, I typically use the following method: $http.post('/auth/signup', user); This code is executed in the controller: app.post('/auth/signup', function(req, res, next) The ...

Exploring the inner workings of MongoDB queries within the context of Node.js

I have a simple search query in Node.js Express.js MongoDB with Mongoose: await Model.find({}).limit(10); My question is about the process flow. Do architects first retrieve all data from Models and then limit to 10, or do they select 10 items directly fr ...

Is submitting with JQuery always a hit or miss?

Hey there, I'm currently working on a problem and could use some help. I seem to be having trouble getting inside my function for form submission in JQuery. Despite setting up console.logs, it appears that my code never reaches the first function. Can ...

Mongodb processes timestamp data in a long format

I'm curious about how to work with timestamps in MongoDB using NumberLong in our database. Which JavaScript function should I use in the MongoDB shell for this purpose? For instance, how can I determine the millisecond time of the next day after a ce ...

ReactJS is in need of extracting certain values from a promise

Within my Firebase database, I have organized data into two Documents: "users" and "posts". Each post in the "posts" collection is linked to a specific user using their unique id from the "users" collection. My goal is to retrieve user data associated wi ...

What is the functionality of Vue plugins in Vite MPAs?

I have developed a Vite application and I am trying to implement multiple pages. I followed the documentation on how to achieve this (link here), but when I start the server, all I see is a blank page. This is what my vite.config.js file looks like: impor ...

Issue with IE7 Dropdownlist not appearing after changing class name when onFocus event is triggered for the first time

I need to adjust the CSS class of a dropdownlist when it is focused on, in order to change its background color. However, in IE7, when the dropdownlist is clicked, the CSS class changes but the options list does not appear until the dropdownlist is clicke ...

Use the on-screen keyboard to move around by using the arrow keys and choose a value from the list to

I am currently working on developing an on-screen keyboard that allows for navigation using arrow keys and selection with the enter key. My goal is to have each selected key append to an input field. Below is the HTML code I have implemented: <div id ...

What is the best way to completely reset a personalized AJAX object?

I've been passing AJAX parameters through a new object and then using that object with jQuery's $.ajax(). However, I'm struggling to fully reset the object. Despite knowing there must be a simple and elegant solution, I haven't been abl ...

Rewrite the nginx configuration to eliminate the "/index.html" part of the URL while preserving the query

My Nginx configuration specifies index index.html as the default index page. When accessing it as a progressive web app (using Angular), the URL loads as /index.html#/route instead of /#/route for some reason. I want to: Check if the URL contains ...

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...

Update the dropdown list once a new record is added to the database using PHP

My PHP dropdown list, created with the CodeIgniter framework, looks like this: <?php echo form_dropdown('empresas', $idEmpresa, 'nombre'); ?> <a onclick=newPopup("http://localhost/ProyectoNetbeans/CodeIgniter_2.1.3/index ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

AngularJS implementation that disables a button when the input field is empty

As I delve into learning angular JS, I am facing a challenge. I want to disable the button using the "ng-disabled" attribute while my input fields for "login" and "password" are empty. However, the default text in the login input is "LOGIN" and in the pass ...

Conditional radio button disabling in Material-ui

Currently, I am developing a React application using material-ui. My goal is to disable all radio buttons within a RadioGroup when a specific event occurs, and then re-enable them once the event is no longer active. For example, when a button is clicked, ...

Utilizing Node.js to Retrieve a POST Request JSON and Modify its Format

Received an incoming Post request in JSON format like this: [{"username":"ali","hair_color":"brown","height":1.2},{"username":"marc","hair_color":"blue","height":1.4},{"username":"zehua","hair_color":"black","height":1.8}] Need to transform it into the f ...

Is there a way to retrieve the field names from a JSON array within a for loop?

Here is the structure of my Json array: var data = { "categories": { "category1": { "Name": "Maps", "Id": 3, "orderInList": 1 }, "category2": { "Name": "B ...

Is there a way to export a variable that has been declared within a function component in React Js?

I am currently developing a React app and I need to export the RoomPricelist1 & FacilityPricelist1 variables. I have assigned values to these variables within a function component but when I try to import them into another function component, they are sh ...