Add items to a fresh record using Mongoose and Express

In my model, I have an array of objects that I want to populate with new items when creating a NEW document. While I have found information on how to achieve this using findAndUpdate, I am struggling to figure out how to do it with the save() method.

This is the structure of my model:

const PettyCashItemsSchema = Schema (
  {
    pettyCashId:{
        type: Schema.Types.ObjectId,
        ref:'PettyCash',
        required: [true, 'La Caja Chica es Obligatoria']
    },
    item: {
        type: Number,
        unique: true
    },    
    items:[{
        concept: {
            type: String,
            maxlength:50,
            required: [true, 'El Concepto es obligatorio']
        },
        incomeAmount:{
            type: Number,
            maxlength:50,
            default:0,
            required: [true, 'El Ingreso es obligatorio']
        },
        expenseAmount:{
            type: Number,
            maxlength:50,
            default:0,
            required: [true, 'El Egreso es obligatorio']
        },
        description: {
            type: String,
            maxlength:50,
            required: [true, 'La Observación es obligatoria']
        },
        status: {
            type: Boolean,
            default: true,
            required: [true, 'El Estatus es obligatorio']
        }
    }],
  }  
);

Below is the code snippet that I am using, but unfortunately, it does not add any new items to the array:

        const pettyCashId= req.params.id;

        const itemToPush = {
            concept: req.body.concept,
            incomeAmount: req.body.incomeAmount,
            description: req.body.description,
            'createdBy':{
                uid: req.uid,
                username: req.user.username,
            }
        };
    
        const item = new PettyCashItems( { pettyCashId, $push: { 'items': itemToPush } } );

        await item.save();

        res.json ( item ); 

Thank you!

Answer â„–1

There's no need to utilize $push when initializing a new document. You can easily establish an array with a single document.

        const recordId= req.params.id;

        const itemToAdd = {
            concept: req.body.concept,
            incomeAmount: req.body.incomeAmount,
            description: req.body.description,
            'createdBy':{
                uid: req.uid,
                username: req.user.username,
            }
        };
    
        const newItem = new CashRecords({ 
             recordId, 
             items: [itemToAdd] 
        });

        await newItem.save();

        res.json ( newItem ); 

When it comes to updating the document and using the .save method, you can employ the Array.push method to append a new item to the items array. However, I'd recommend utilizing findOneAndUpdate for updating documents. Below is an example demonstrating the use of .save during updates.

const recordId= req.params.id;

const itemToUpdate = await CashRecords.findOne({ recordId });

const itemToAdd = {
    concept: req.body.concept,
    incomeAmount: req.body.incomeAmount,
    description: req.body.description,
    'createdBy':{
        uid: req.uid,
        username: req.user.username,
    }
 };

itemToUpdate.items.push(itemToAdd)

await itemToUpdate.save();

res.json(itemToUpdate); 

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 am running into an issue where the Google App Engine standard is not able to compress my Next.js/Express

I am currently exploring solutions to enable compression on the output of my Next.js/Node.js/Express application when deployed on Google App Engine (standard version). It appears that the issue lies in the fact that: 1) Google's load balancer strips ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

"Use Highcharts to visually compare the data from one month in two different years

How can I use Highcharts Columns to compare data from two different years within the same month? Check out the example image below: https://i.sstatic.net/8MMsA.png The data structure is as follows: myData[0] = { data1:"0.00", data2:"0.00", data3:"868.0 ...

The consequences of jQuery Ajax Memory Leaks

After reading through several other posts on the topic, I have noticed a memory leak issue when making repeated ajax calls with jQuery (every 30 seconds in my case). Switching from using $get to $post helped reduce the size of the leak, but it still occurs ...

The "require" keyword cannot be used in a Node-RED Function node

When working with a Node-RED Function Node, the first line I include is: var moment = require('moment-timezone'); I'm attempting to create a timezone accurate date/time stamp for sensor data. However, when this node runs, I encounter the fo ...

Currently, I am developing a customized stylesheet specifically designed for Internet Explorer versions 10 and 11

Is it possible to utilize this straightforward script for identifying IE versions 10 and 11? if($.browser.version == 11.0 || $.browser.version == 10.0) { $("body").addClass("ie"); } ...

In my development environment, the page does not have scroll functionality, but in the production environment, it is scrollable

Whenever I open a table or any other element with overflowing content, I encounter an issue with the scrolling bar. Even though the CSS includes overflow-y: scroll;, the scroll bar on the right remains in gray and does not allow me to scroll down when the ...

Is there a way to use a single function to fill and calculate multiple input fields with PHP, Javascript, and

I've encountered an issue while trying to populate a form using Javascript/ajax/php. The problem is that my function only fills in one of the required forms and then stops, even though I have received the second response from the server. Here's ...

I am sending JSON as form data using JavaScript and then accessing it in PHP. During this process, the quotation marks are being replaced with their HTML entity equivalent

After converting an array into JSON, I send it as a value of a text box using the post method. In a PHP file, when trying to print it out, it displays some encoding issues. var json_arr = JSON.stringify(info); The generated JSON looks like this: {"1":"1 ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

In React Router, redirect when location.state is not defined

import React, { useState } from "react"; import { Redirect } from "react-router-dom"; function Update(data) { if(!data.location.state) return <Redirect to="/"/> const [name, setName] = useState(dat ...

Is there a more efficient method for writing my jQuery code that follows a step-by-step approach?

I have developed a step-by-step setup process that guides users through various sections. Instead of using separate pages for each step (like step1.php, step2.php, etc.), I have all the code contained in one page named setup.php. This is achieved by utiliz ...

When attempting to sort, I encounter two errors that seem to be interconnected. The first error states "TypeError: cart is not a constructor" in the post method, while the

Uncaught ReferenceError: cart is not a constructor I have been using these technologies for over a year and have never encountered such issues before, so please help me out. router.post('/add-to-cart', isLoggedIn, function (req, res, next) { ...

The userscript is designed to function exclusively on pages originating from the backend, rather than on the frontend in a single-page application

I have a userscript that I use with Greasemonkey/Tampermonkey. It's set to run on facebook.com, where some pages are served from the backend during bootstrapping and others are loaded on the fly in the front-end using HRO, similar to how a Single Pag ...

Obtaining parameters with express in node.js

It seems like such a simple task, but I can't seem to figure out why it's not working. I'm attempting to create an application where a user can search for something, receive a link, and when clicked, it calls a second route while passing a ...

Efficient method to access two arrays simultaneously and combine them into an associative array in JavaScript

When using Ajax to return a table, you have the option of separating column names and row values. Here are two ways to do it: let columns = ["col1", "col2", "col3"]; let rows = [ ["row 1 col 1", "row 1 col 2", "row 1 col 3"] , ["row 2 col 1", "r ...

What is the process of encoding a String in AngularJS?

Utilizing Angularjs for sending a GET HTTP request to the server, which is then responded to by the Spring MVC framework. Below is a snippet of code depicting how the URL is built in Angular: var name = "myname"; var query= "wo?d"; var url = "/search/"+qu ...

What is the process for configuring the index type as 'text' in MongoDB Compass?

While utilizing MongoDB Compass, I am attempting to create an index with the type 'text'. Despite following the instructions provided on https://docs.mongodb.com/manual/indexes/#single-field, I was unable to successfully create an index with the ...

Highcharts Maps - Circular zoom controls

Currently implementing the Highcharts API for a special project. All features are functioning well except for one issue. I am looking to make the zoom in/out buttons appear rounded. I have attempted using border-radius with 50%, as well as modifying the r ...

Tips on adding background images to your chart's background

Is there a way to set an image as the background in Lightning Chart using chartXY.setChartBackground? ...