Unable to insert a JSON object into an array using JavaScript and MongoDB

I'm encountering an issue when trying to push data into my Student model with the following schema:

var StudentSchema = new Schema({
    firstName: {
        type: String,
        trim: true,
        default: ''
        //validate: [validateLocalStrategyProperty, 'Please fill in your first name']
    },
    lastName: {
        type: String,
        trim: true,
        default: ''
        //validate: [validateLocalStrategyProperty, 'Please fill in your last name']
    },
    worksnap: {
        user: {
            type: Object
        },
        timeEntries : [],
    },
    timeEntries : []
});

My JavaScript code for pushing items looks like this:

Student.findOne({
            'worksnap.user.user_id': item.user_id[0]
        })
        .populate('user')
        .exec(function (err, student) {
            if (err) {
                throw err;
            }
            //student.timeEntries.push(item); // this works
            student.worksnap.timeEntries.push(item); // this does not work
            student.save(function (err) {
                if (err) {
                    //return res.status(400).send({
                    //    message: errorHandler.getErrorMessage(err)
                    //});
                } else {
                    console.log('item inserted...');
                }
            });

        });

Although pushing items into the timeEntries array outside the worksnap object functions correctly, I am facing issues when trying to do the same within the worksnap object. I'm unsure why this discrepancy exists.

Do any alternatives exist for adding JSON objects into an array type in MongoDB?

Thanks

Answer №1

Implement the .lean() method

When using the lean option in queries, the returned documents are plain JavaScript objects without MongooseDocument features. They lack save methods, getters/setters, or other Mongoose functionalities.

Student.findOne({
    'worksnap.user.user_id': item.user_id[0]
  })
  .populate('user')
  .lean()//-----Added!
  .exec(function(err, student) {
    if (err) {
      throw err;
    }
    //student.timeEntries.push(item); // this works
    student.worksnap.timeEntries.push(item); // this does not work
    student.save(function(err) {
      if (err) {
        //return res.status(400).send({
        //    message: errorHandler.getErrorMessage(err)
        //});
      } else {
        console.log('item inserted...');
      }
    });

  });

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

``Protect your PDF Document by Embedding it with the Option to Disable Printing, Saving, and

Currently, I am facing a challenge to enable users to view a PDF on a webpage without allowing them to download or print the document. Despite attempting different solutions like Iframe, embed, PDF security settings, and Adobe JavaScript, I have not been s ...

Creating a stylish button using a combination of CSS and Javascript classes within a webpage layout

Is it feasible to include a button in the layout that has HTML, CSS styles, and JavaScript functionality? For instance: This button is designed with both CSS styling and JavaScript classes. How can one incorporate CSS and JavaScript along with HTML conte ...

Guide on using JavaScript to extract and display a random text from a datalist upon clicking with the onclick event

Is there a way for a JavaScript function to select a random sentence from a datalist within the same file and display it upon clicking a button with an "onclick" event? I'm new to JavaScript and seeking the simplest solution. Can anyone provide an exa ...

Only switch a radio button when the Ajax call results in success

Within an HTML form, I am working with a group of Radio buttons that trigger an Ajax call when the onchange() event is fired. This Ajax call communicates with the server to process the value sent by the call. The response can either be a string of "succes ...

Interacting between C# and Node.js

I am looking to develop a GUI application using C# that will serve as a platform for Node.js. Specifically, I want to utilize Node's file system API to read files from a directory, and have my C# program generate a list (similar to a ListView) to show ...

What's causing this sluggish performance?

I'm in the process of developing a Google Chrome extension and I can't help but wonder why window.onload = loadPage; function loadPage() { document.getElementById('nav-robux-amount').innerHTML = '0'; console.log(" ...

Utilizing media queries to customize the appearance of a jQuery accordion widget

Hello, I'm struggling with implementing a jQuery accordion for mobile platforms that destroys itself on larger screens. While my code is mostly working, I've encountered two issues: The accordion only gets destroyed when the window is resized ...

Node.js sends a request to open a new GET method, querying the specific HTML file at "what.should.I.put.here.html/getAll", with the option for

After designing the majority of my website, I decided to host it on a school-based hosting service. My files are organized into two folders: a client folder with my html pages and main.js file, and a server folder containing the API that main.js accesses. ...

Troubleshooting: Vue Component Unable to Locate Property

Just dipping my toes into Vue with a simple test implementation and running into some trouble breaking down data into components. Let's take a closer look at the code: <body> <header id="main-header"> <custom-header></ ...

Exploring MongoDB query conditions and result projections

I am in the process of developing an application using Node/Express/MongoDB/Mongoskin. Within the database, there is a collection named "clients" that contains documents with information about client accounts. Each client document includes an array that h ...

Ways to retrieve information from a specific key

I'm currently facing a challenge accessing specific data objects that are referenced by keys. In this particular scenario, the "applicant" data is nested within an Event object. My goal is to extract this data and create a new object from it. While I ...

What is the process for retrieving data from mongoDB and displaying it by year in a single row?

I have received an array of data from MongoDB, which includes id, userName, and date. The date consists of years and months. My goal is to display this data categorized by years. How can I construct a query to the database that will show the data for all y ...

Error: Discord bot encountered a TypeError while attempting to access the property 'id' of an undefined value

After revisiting a previous Discord bot package designed to track website updates, I encountered an issue. The code was originally scraped and last edited about 8 months ago with success. However, upon running node index.js, the following error occurred. ...

React-select: The default values will only be updated if they are initially set statically

Need help displaying a list of interests from backend data: profile : { interest: ["interest1", "interest2"], }; This is my implementation: import Creatable from "react-select/creatable"; class EditProfileInSettings exten ...

A guide on displaying data in a table using a select dropdown in a pug file and passing it to another pug file

After creating a single page featuring a select dropdown containing various book titles from a JSON file, I encountered an issue. Upon selecting a book and clicking submit (similar to this image), the intention was for it to redirect to another page named ...

Error: The property 'create' of undefined cannot be read (Material UI/enzyme)

When I mount a component, I encounter an error that does not occur when using shallow rendering. The specific error is: TypeError: Cannot read property 'create' of undefined at stylesOrCreator (node_modules/@material-ui/core/CircularProgress/C ...

Problem with CSS: In Chrome, text fields have 3px additional margin-right

https://i.sstatic.net/I8mzi.jpg I am facing an issue with the margins of my text fields. Even though I have set a margin-right of 5px for each field, Google Chrome seems to be adding an additional 3-4px automatically. This problem is evident when I dynami ...

Storing JSON data in a MongoDb database using the Sails.js framework

I'm looking to build my database using an external API. To begin, I've created a function called loadData(req, res){} in my DBController that retrieves data from the API in JSON format. Now, I want to save this imported JSON data into my mongoDB ...

Creating Scroll Animations in Javascript - Mastering scrollIntoView Animation

When I click on a div, I was only able to bring it into view with the scrollIntoView function. It functions correctly and meets my expectations, but I am curious if there is a way to animate it and slow down the process. I attempted a suggestion found her ...

Building conditionals in AngularJS expressions using if-then-else syntax

Is there a way to incorporate the ternary-operator (if-then-else construction) in an angularjs expression? For example, I have a function $scope.isExists(item) that should return a boolean value. I would like to do something like this: <div ng-repeater ...