What is the best way to use the $push operation to add an object to an array within a mongoDB database using Node.js

I am trying to find a way to push an object into an array inside my MongoDB database. When using the $push method with submits[postDate], I am encountering an error with the syntax highlighting the first "[". Any suggestions on how to resolve this issue?

Here is my code snippet:

        app.post('/add-submit', (req,res) => {

        let postDate = new Date();
        let dd = String(postDate.getDate()).padStart(2, '0');
        let mm = String(postDate.getMonth() + 1).padStart(2, '0');
        let yyyy = postDate.getFullYear();

        postDate = mm + '/' + dd + '/' + yyyy;

        subject = req.body.subject

        let pushValue = {
            time: req.body.time,
            description: req.body.description,
            date: postDate 
        }
            
        console.log(pushValue)

        console.log(postDate)

        let myquery = { username: req.body.username};
        let newvalues = { 
            $push : {
                "submits.$[postDate]" : {
                    "[subject]" : pushValue 
                }
            }                               
        }
        db.collection("users").updateOne(myquery, newvalues, (err, response) => {
            if (err) throw err;
            console.log("1 document updated");
            res.redirect('/users/'+req.body.id)
        });   
    })

However, I keep encountering the following error:

    D:\Users\willi\Documents\Node\StudyWebApp\server.js:186
                submits[postDate] : {
                       ^

SyntaxError: Unexpected token '['
    at wrapSafe (internal/modules/cjs/loader.js:1053:16)
    at Module._compile (internal/modules/cjs/loader.js:1101:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...

This is the structure I want in my database:

https://i.stack.imgur.com/U8jFA.png

Thank you.

Answer №1

Your object model may not be very clear, but it seems like you need to use the $ keyword.

Instead of trying to get the position in 'submits' with submit[postDate], you should do something like this:

db.collection.update({
  "username": "test",
  "submits.date": "16/10/2020"
},
{
  $push: {
    "submits.$.subjects": {
      "subjectName": {
        "time": "1234",
        "description": "desc"
      }
    }
  }
})

Let me explain how it works, it's actually quite simple.

The first object is where you are pointing to. It's like a 'find', indicating the part of the document where you want to perform the second action (the push). By using the $ operator, you are specifying exactly which part of the document to work on.

Therefore, the second object ($push object) represents the operation to be performed. Using submits.$.subjects, the operation will be carried out at that specific section of the document.

I haven't tested it in Node, but since your code includes variables like myquery and newvalues, it should function in the same way.

On a side note, I have responded to the query here

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

Unresolved promise rejection on Repl.it

I decided to add a basic leaderboard feature to my game on Repl.it, so I set up a node.js backend for it. Here's the code snippet for the backend: const express = require('express'); const Client = require('@replit/database'); cons ...

Guide to running code repeatedly in node.js

Is there a way to repeat the console.log function 5 times in Node.js using the 'repeating' npm package? I am working on a node application that needs to run a specific code multiple times, but I can't seem to figure out how to achieve this. ...

When I run 'npm install', I am looking to automatically download additional resources by utilizing a 'prepublish' script

Is it possible to download angular.min.js during the 'npm install' process? I came across this information which suggests using a prepublish script for such tasks. It also states that there's no need to have wget/curl installed on the syste ...

Leverage the data from a local JSON file within a web application built with Vue CLI 4.2.3

I need to use a JSON file to store some data and utilize them in the components. [ { "heroTitle": [ "Banner image", "assets/images/banner/sunset.jpg", "sunset.jpg" ], } ] The above JSON is an example, and below is my compone ...

Is there a way to utilize a POST request to pass a React component from server.js to App.js for rendering?

I am new to React and JavaScript and still in the learning process :) I'm working on a magic 8 ball application where, upon clicking the button using the post method, I aim to retrieve a random answer (one of the 20 in my server.js) back to the same ...

What is the process of handling XML responses using node.js and express?

My task is to handle this using node.js and express: <set id="1" state="0" name="wd"/> I attempted the following approach: xml = require('xml'); res.set('Content-Type', 'text/xml'); res.send(xml('<set id="1" ...

JSON file organization

Is it possible to convert the integer values highlighted in the code snippet to string values? You can check out the image at the following link for reference: https://i.stack.imgur.com/3JbLQ.png Here is the code snippet: filename = "newsample2.csv&q ...

Order JSON array based on the time, extract the pairs of keys and values, and transfer them to a Google

My goal is to extract the most recent entry from a JSON array stored in a Google Sheet and copy it into two adjacent columns. The desired data resides in Column L of my spreadsheet (starting from row 2) and follows this format: [{"id": "XX:123456", "time ...

Issue encountered with Bing webmaster API when retrieving keyword statistics: an unknown error occurred resulting in an empty

My goal is to retrieve keyword statistics through the bing webmaster API using JSON GET requests. The required parameters for this operation are as follows: List<KeywordStats> GetKeywordStats( string q, string country, //optional s ...

Start the Python program exclusively instead of displaying the Linux Graphical User Interface upon startup

Is it feasible to deactivate the Linux GUI rendering and restrict access to the system, only displaying the Python (or Node.js) script upon startup? I aim to execute a Python or Node.js script with its own GUI in fullscreen mode and lock it down, while s ...

jsonAn error occurred while attempting to access the Spotify API, which resulted

Currently, I am working on acquiring an access Token through the Client Credentials Flow in the Spotify API. Below is the code snippet that I have been using: let oAuthOptions = { url: 'https://accounts.spotify.com/api/token', method: ' ...

Strip  symbol out of json output

Currently, I am utilizing the Volley Library to parse JSON data. However, when parsing the response, it contains a certain symbol at the beginning: JSON RESPONSE : {"category":{"420":{"key":420,"label":{"420":"Acacia"},"count":"1"},"421":{"key":421 ...

Problem with character encoding in Node.js

I am encountering an issue while retrieving data from a request, as the formatting or encoding is not matching my requirements. Attempted to address this by setting the encoding with req.setEncoding('utf8') The expected string should appear as: ...

I've been waiting forever for Product.find() to return some results, but it seems to

I have been encountering an issue where my code is supposed to return an empty object of a product but instead it just keeps loading forever. I have thoroughly checked through the code and explored every possible scenario where an error could be occurring, ...

Is it possible to seamlessly transition an express app to meteor?

Currently working on migrating an app from node.js with express framework to meteor. Attempting to reverse engineer the process using a method similar to https://github.com/onmodulus/demeteorizer ...

Exploring the power of real-time queries with Stubby4node

I'm attempting to achieve the following: # Finding Destination by ID - request: .... query: serviceId: "s009" response: file: destinations/destination-by-service-id-$serviceId.json ... My goal is for the serviceId to correspond with ...

nvm-windows: unable to execute globally installed programs

I recently set up multiple versions of node on my Windows 7 system using nvm. Currently, I am working with node v8.0.0 and have globally installed express. npm install -g express However, when attempting to create a new app using express testapp, I enco ...

GSON encountered a JsonSyntaxException, with an expectation of a name at line 7, column 4

In my project, there is a Result class that has various properties and is intended to be returned as JSON. public class Result { public String objectid; public String dtype; public String type; public String name; public String descrip ...

Creating a dictionary in Python by parsing a text file and troubleshooting printing errors

After successfully reading a text file, creating dictionaries per line, updating (appending) each line, and storing the json file, I encountered an issue. The problem arises when trying to read the json file, as it fails to do so correctly. Could this be r ...

Converting a String into an Array using JSON

My dilemma involves converting an Array of Json elements from a String to an Object Array using Gson. Despite researching methods online, none of them seem to properly address my specific scenario. ["2": {"id": 2, "name": "Cannonball", "sp": 5, "overall_a ...