Perform the action: insert a new item into an array belonging to a model

Here is the structure of my model:

var userSchema = new mongoose.Schema(
    {
        userName: {type: String, required: true},
        firstName: {type: String},
        lastName: {type: String},
        password: {type: String, required: true},
        email: {type: String},
        profileImg: String,
        weight: {type:Array, default:[]},
        schedules: {type: [schedule], default: []},
        dateCreated: {type: Date, required: true, default: Date.now},
    }
);

I'm encountering an issue with the 'weight' field which should only contain numbers. When trying to update and push a new number into it, I observe unexpected behavior on the server side:

  var data = req.body;
    var _id = req.params.userid.replace(new RegExp('"', 'g'), "")
    User.findById(_id, fieldsFilter, function (err, user) {
        if (err) return next(err);
        console.log('*********', data.weight)

        if (user) {
            user.userName = data.userName ? data.userName : user.userName;
            user.firstName = data.firstName ? data.firstName : user.firstName;
            user.lastName = data.lastName ? data.lastName : user.lastName;
            user.email = data.email ? data.email : user.email;
            //TODO check if weight is in correct form
            // HERE!!
            user.weight = data.weight ? user.weight.push( data.weight) : user.weight;
            user.save(onModelSave(res));
            console.log(user.weight)
        } else {
            //user does not exist create it
            var newUser = new User(data);
            newUser._id = ObjectId(req.params.userid);
            newUser.save(onModelSave(res, 201, true));
        }

When looking at the log outputs, I see that data.weight has the value 5, but after processing, the array contains just 1. I am struggling to identify the root cause of this inconsistency.

Your help is greatly appreciated.

Answer №1

The issue at hand is as follows:

user.weight = data.weight ? user.weight.push(data.weight) : user.weight;

If the value of data.weight exists, you are assigning the result of user.weight.push() to user.weight. This will be the new length of the array (which will be 1 if user.weight was empty before).

It seems like what you really intend to do is this:

if (data.weight) {
  user.weight.push(data.weight);
}

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

The React Component is limited to updating once

Exploring the React Native code below: import React from 'react'; import {Text, View, StyleSheet, Button} from 'react-native'; export default class Target extends React.Component { constructor(props){ super(props); ...

Guide on creating a square within an element using JavaScript

After conducting thorough research, I find myself unsure of the best course of action. My situation involves a Kendo Grid (table) with 3 rows and 3 columns. Initially, the table displays only the first column, populated upon the page's initial load. S ...

The preflight request's response failed to meet the access control criteria due to the absence of the 'Access-Control-Allow-Origin' header

I encountered an issue while using ngResource to call a REST API hosted on Amazon Web Services: Upon making the request to , I received the following error message: "XMLHttpRequest cannot load. Response to preflight request doesn't pass access cont ...

Guide to implementing a variable delay or sleep function in JQuery within a for loop

I've noticed that many people have asked similar questions, but none of the solutions provided seem to work in my specific case. My goal is to incorporate a delay within a for loop with varying time lengths. These time lengths are retrieved from an a ...

Failure to display alert message upon completion of AJAX request

I am attempting to use AJAX to send data to the database without refreshing the page when a user favorites a message. Even though the data is successfully sent to the DB, the page still reloads and the alert message I want to display is not showing up. Th ...

What is preventing images from displaying in my slider within baguetteBox?

Currently, I am in the process of incorporating a slider into my website using the baguetteBox library. After consulting the documentation, I successfully implemented an example that is functioning smoothly without any issues. In order to display a series ...

Having difficulty interacting with a button using Selenium and JavaScript

For some reason, I am experiencing difficulty in clicking the login button even though my code appears to be accurate and there are no iframes or windows present: const { Builder, By, Key, until } = require('selenium-webdriver'); const { expect ...

One Functionality on Button is Failing to Execute among Several Tasks

I've encountered an issue with one of the tasks triggered by a button click. The button successfully executes two out of three tasks (hides them on click), except for the last task which involves a text-blinking JavaScript function. I've used the ...

Issues arising with transferring information between components

My webpage had a header with a search engine input, a list of posts, and pagination all on one page. I made the decision to separate the header into its own component in a different Vue file. However, after making this change, searching for posts by their ...

Having difficulty locating the index of the column labeled `Clients` within a table; the result being -1

Having some trouble locating the index of the column name Customers within a table using jQuery/javascript. No matter what I try, it always returns -1 let tableDatacy = "Results_Table"; let columnName = "Customer"; let tableHeaders = [] ...

Reaching the maximum request threshold

Currently, I am facing an issue where users are able to upload files from the client side (using Angular 4) to the server (implemented with Spring Boot). The problem arises when a user attempts to upload more than 6 files at once. In such cases, Chrome uti ...

Preventing all hammer.js (angular-hammer) interactions except for single taps

Utilizing the angular-hammer module in my app, I am keen on refining its performance specifically for the tap event. Given that no other gestures are required, I aim to enhance efficiency by excluding unnecessary listening functions, such as double tap. As ...

"Before the click even happens, the jquery click event is already

As I was developing a small todo app, I ran into an issue where the alert message seemed to pop up before the click event was triggered. It almost seems like the event is not registered properly. Can someone explain why this is happening? (function() { ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

Issue with custom validator in Angular 6: setTimeout function not functioning as expected

Currently, I am in the process of following a tutorial to implement Asynchronous validation in Angular. The goal is to create a custom validator named shouldBeUnique that will be triggered after a 2-second delay. To achieve this, I have utilized the setTim ...

Guide on how to bundle a TypeScript project into a single JavaScript file for smooth browser integration

I am currently working on a small project that requires me to write a JavaScript SDK. My initial plan was to create a TypeScript project and compile it into a single JavaScript file, allowing users of my SDK to easily inject that file into their web pages. ...

Unable to establish connection with Uploadthing due to a timeout error

I am facing timeout errors while setting up the upload feature. app/api/uploadthing/core.ts import { createUploadthing, type FileRouter } from "uploadthing/next"; import { auth } from "@clerk/nextjs"; const handleAuth = () => { c ...

Having trouble getting a hold of react router 4 and express: cannot retrieve data

Hey there, I'm currently working on implementing React Router 4 with an Express server. When I set the path to "/", everything works smoothly. However, when I change the path to "/test" and try to visit the test page, I encounter the error "Cannot GE ...

Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Ca ...

Unable to load JSON model texture

I successfully transformed an obj file into a json model using a Python tool, and now I am attempting to load it into my project. Below is the code snippet: var camera, scene, renderer; var mesh, aircraft; function addModelToScene( geometry, materials ) ...