What is the best way to insert a value into a MongoDB document using a for loop?

I am looking to save each day of the year in the Mongo Database but I'm unsure about the best approach. I have tried using the $push method and .update method, however, neither seem to be suitable for this scenario.

This is my controller:

exports.reflux = (req, res) => {
    const newDay = new Calendar();

    for(let i=3; i<367; i++) {
        newDay({$push: {day: new Date(new Date().getFullYear(), 0, i), offWork: true, description: ' '}});

    }
    // for(let i=3; i<367; i++){
    //
    //     {$push: {newDay.day = new Date(new Date().getFullYear(), 0, i);}}
    //     newDay.day =
    //     newDay.offWork = true;
    //     newDay.description = '';
    // }

    newDay.save();

};

The desired outcome is a collection of documents representing each day of the year.

Answer №1

If you're looking to add multiple entries in one go, consider using the insertMany method.

Start by creating an array of objects representing each day and then use insertMany to add them all at once.

let days = [];
for(let i=3; i<367; i++) {
    days.push({day: new Date(new Date().getFullYear(), 0, i), offWork: true, description: ' '});
}

newDay.insertMany(days, function(err) {

});

Answer №2

Alright, completed.

exports.redux = (req, res) => {
    for(let i=3; i<367; i++) {
        const newEvent = new Calendar();
        newEvent.date = new Date(new Date().getFullYear(), 0, i);
        newEvent.offWork = true;
        newEvent.notes = '';

        newEvent.save(err => {
            if(err) {
                console.log('error');
            }
        });

    }

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

Can I use MuiThemeProvider in my component without any restrictions?

I have a unique component called View: import React from 'react'; import { AppBar, Toolbar } from 'material-ui'; import { Typography } from 'material-ui'; import { MuiThemeProvider, createMuiTheme } from 'material-ui/st ...

Leveraging the count feature in MongoDB aggregations

My goal with the aggregation below is to determine the number of conversations resolved by either a Chatbot or an Agent during office hours and outside of office hours. Currently, the aggregation results in a set of documents showing the difference between ...

Oops! It seems like there's a problem with reading the 'strEmail' property of undefined. Do you have any ideas on how to fix this issue

Currently, I am working with Express.js to create a straightforward login post request. Here is the code snippet: app.post("/login", (req, res) => { res.send( { isUserRegistered: userLogin(req.body.strEmail, req.body.strPassword), ...

The conflict between ESLint's object curly new line rule and Prettier's multi-line formatting

I'm brand new to the world of prettier, typescript, and eslint. Even though most of the integration is going smoothly, I am facing an issue with multi-line destructuring objects. Prettier Version 1.19.1 Playground link Input: const { ciq, draw ...

JavaScript Removing Event Listener with Callback and Parameter

I am currently attempting to implement the following: el.addEventListener('scroll', callFunc); el.removeEventListener('scroll', callFunc); However, I want to use a callback function with parameters like this: el.addEventListener(&apos ...

How to seamlessly upload an image in PHP without the need to refresh the page

Can anyone provide guidance on how to upload an image without having to refresh the page? I have been searching for solutions but haven't found a suitable one yet. ...

Tips for effectively implementing a curried selector function with the useSelector hook in react-redux

In my project using react-redux with hooks, I encountered a situation where I needed a selector that takes a parameter which is not passed as a prop. Upon checking the documentation, it mentioned: The selector function does not receive an ownProps argum ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Replicate the styling of CSS class A and apply it to class B

Let's take a look at some code: <button id="test" class="ui-state-hover" value="Button"> In Context: I'm utilizing the JQuery UI CSS class ui-state-hover on an HTML button to ensure it always appears as if it's being hovered over. H ...

Issue with code failing to insert object into an array

I've been struggling to add a group of objects from a JSON file into an array. Despite trying to use the push method, the length of the array remains at 0. I'm puzzled by what could be going wrong. The JSON data is being parsed correctly as I&apo ...

Transferring data with Node express in and out of applications

As I embark on my first Node project, a friend advised me to create a .js file for common and frequently used functions. For instance, when performing operations with Mongoose such as querying data or updating it, having a separate .js file for these task ...

Obtaining an XML element within an XSLT transformation

I need to retrieve the value of an XML element within XSL. Although my JavaScript is able to select one XML document, there are elements in other documents that I also require. I am uncertain if this task is feasible or if my syntax is incorrect. This is ...

Adjust the speed of the remaining divs below to move up when one is deleted using Ajax and jQuery

My div elements are arranged from top to bottom, and when one selected div is removed or faded out, all other divs below it shift up suddenly to fill the gap. While this behavior is functional, I would prefer to slow down the movement of the divs shifting ...

Encountering a 400 error while trying to implement file upload feature in Spring AngularJS -

Whenever I attempt to upload a file using Spring and AngularJS, I keep encountering the dreaded 400 Bad Request error: > error: "Bad Request" > exception: "org.springframework.web.multipart.support.MissingServletRequestPartException" > message: " ...

No results found using AngularJS UI-Bootstrap Typeahead

I've been searching around but haven't found any questions related to this topic. Currently, I am utilizing Angular UI-bootstrap typeahead feature. Here is what I have implemented: <input type="text" ng-model="loc" typeahead="location for l ...

Tips for correctly shutting down a server running Jackrabbit and MongoDB

Our Java application built with Spring Boot utilizes Jackrabbit in conjunction with MongoDB. Below is the configuration for MongoDB: @Configuration @Profile("production") public class MongoRepositoryInitializer { @Value("${oak.mongo.db}") private ...

Is it possible for the HTML data attribute to store a direct link to a specific DOM element?

Can the HTML data- attributes be used to store a reference to another DOM element? As shown in this jQuery example: var domel1 = document.getElementById("#mydiv"); var domel2 = document.getElementById("#mydiv2"); $(domEl1).attr('data-domel', dom ...

Error: Fetch function does not exist

My goal is to periodically update my HTML page by fetching data from my Express API. Unfortunately, I'm facing challenges when it comes to integrating this functionality into Pug. Both fetch and XMLHttpRequest are resulting in the same error message: ...

Adjusting the dimensions of a div to accommodate varying text lengths

I'm currently facing an issue where I have multiple divs all sharing the same "Text" class. These divs don't have set width or height values, and are adjusting based on the content inside them, which varies in width. The problem arises when other ...

Concerns with the performance of Leaflet's polyline

Currently using Leaflet version 1.0.3 and encountering an issue with GPS positions on my map. Within a for loop, I am creating circle markers for each GPS position: var position = new L.latLng(lat, lng); coordinates.push(position); L.circle([lat, lng], ...