Issues with Javascript causing MongoDB batch insert to fail

I need assistance with optimizing my Javascript code. I have created a script to insert multiple records into a collection at once using "insertMany()". However, the code I wrote is not functioning correctly:

var batch = [];
for (i=0; i<10; i++) { 
    names=["exam", "essay", "quiz"]; 
    for (j=0;j<3;j++) { 
        batch += '\n{ student : ' + i + ', type : "' + names[j] + '", score : ' + Math.round(Math.random()*100) + '}' ;
        if (mod i%3 == 0) {
            batch = batch.slice(0, batch.lenght(-1));
            db.scores.insertMany( batch )
            batch=[];
        }
    }
}

There are a couple of issues with this code. Firstly, the array items are enclosed in double quotes, and secondly, the "slice" method is not functioning as expected.

I am looking for help in resolving these issues and optimizing the Javascript code.

Answer №1

Here are a couple of issues that need to be addressed:

The array items are surrounded by double quotes.

To create an object instead of a string, you should use

batch = { student: i, type: names[j], score: ..}
.

The "slice" method is not having any effect.

It seems like you are trying to use batch.slice(0, batch.lenght(-1)), but there are a couple of mistakes here. First, you misspelled length. Also, length is a property, not a function. You can simply use batch.slice() if you want to copy the array, although in this case, it's unnecessary since you are resetting the array.

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

Continuous Playback of Sound

Is there a way to autoplay an audio in loop without being blocked by browsers? Code : <audio id="audio1" src="assest/sound/1.mp3" autoplay="" /> <script> a = document.getElementById('audio1&apo ...

What is the process of transforming a JSON string into a JavaScript date object?

{"date":"Thu Dec 06 14:56:01 IST 2012"} Is it possible to convert this JSON string into a JavaScript date object? ...

How can I use the coffee CLI to assign variables to the necessary files?

It has come to my attention that there's a way to accomplish something similar to the following: coffee -r "_=underscore" When working with JavaScript, it seems there is no automatic loading of constants. This means that anything you export requires ...

Chunk loading in IE 11 has encountered an error

Having an issue with my website which is created using Angular 5. It seems to be malfunctioning in IE 11, and I am encountering the following error in the console: https://i.stack.imgur.com/Ek895.png Any insights on why my Angular code isn't functio ...

Unable to add items to the collection in NPM with Meteor 1.3

I have encountered an issue with the imap-simple NPM package while trying to perform an insert operation. Despite following the suggestions on , I am still unable to get the insert function to work properly! Even after simplifying the code and eliminatin ...

Limit the jQuery dialogue button to just one click

My goal is to create a jQuery dialogue box that sends data when the 'OK' button is clicked. The challenge I'm facing is making sure it only sends the data once, regardless of how many times the button is clicked. $.dialogue({ ...

changing the validation function from using if statements to utilizing switch statements

Currently, I am refactoring a form in react and planning to offload most of the state and logic to the parent component. This decision is made because the parent's state will be updated based on the form submission results. However, I encountered an i ...

Guide to Implementing npm Package 'latlon-geohash' in Angular 7

I'm encountering an issue while attempting to utilize the latlon-geohash npm package within my Angular 7 application. When I execute it, I encounter the following error... ERROR TypeError: latlon_geohash__WEBPACK_IMPORTED_MODULE_8__.encode is not ...

The Angular filter is waiting for the ng-repeat to be populated

I have a filtering system that includes dropdown options to filter the displayed content. The content is fetched from a database and takes a few milliseconds to display. During this time, I encounter several errors related to the filtering system. Does any ...

What is the best way to completely eliminate a many-to-many relationship with a custom property?

I have encountered a situation where I am utilizing an entity setup similar to the one explained in this resource. The problem arises when I try to remove entries from post.postToCategories. Instead of deleting the entire row, TypeORM sets one side of the ...

Show specific button text when no file has been selected

I have a form with an image container that allows users to change the photo. The icon opens a file browser, and when the user selects a file, the Change button submits the photo and updates it. https://i.sstatic.net/R5vwn.jpg If no file is selected, I wa ...

The property 'push' cannot be read because it is undefined

$scope.AddTask = function () { $scope.tasks.push([{ "taskName": $scope.taskName, "priority": $scope.selectedP }]); }; $scope.tasks = [{ "taskId": 1, "taskName": "task 1", "priority": 1 }, { "taskId": 2, "taskName ...

Creating nested namespaces with interfaces in Typescript type definitions

In my Javascript project, I am trying to define typing for a specific structure. Consider the following simplified example: a | + A.js + b | + B.js Here we have a folder 'a', and inside it there is another folder 'b'. My goal is t ...

Exploring Array Iteration: Navigating through Arrays with the .map Method in React and Vue

I am currently using Vue after coming from a React background. In React, there is a method called .map that allows you to render a component multiple times based on the number of items in an array and extract data from each index. Here's an example: f ...

Tips for sorting through various elements or items

How can I improve my filtering function to select multiple items simultaneously, such as fruits and animals, or even 3+ items? Currently, it only allows selecting one item at a time. I attempted using , but it had bugs that displayed the text incorrectly. ...

PHP Ajax file uploads can be tricky, as they often result in the frustrating "undefined

Encountering issues with submitting file through ajax. Despite following instructions from various sources, the formdata does not seem to contain the file resulting in an 'undefined index 'image'' error. <form enctype: 'multip ...

Showing JSON object in an Angular 2 template展示JSON对象在模

When I execute the following code: stanservice.categoryDetail(this.params.get('id')) .then((data) => { this.category = JSON.stringify(data.res.rows[0]); console.log(JSON.stringify(data.res.rows[0])); }) .catch((error) => { ...

Tips on integrating Codrops tutorial codes into a SilverStripe website project

Exploring the vast array of tutorials and code examples on the Codrops site has been an enlightening experience. Codrops Website I'm eager to incorporate some of these resources into my SilverStripe projects as well. SilverStripe CMS After learning h ...

Convert time display to a 24-hour format using JavaScript

I managed to convert the time format from GMT to my browser's local time using the following JavaScript code: var newDate = new Date(timeFromat); timeFormat = newDate.toLocaleString(); Now, I want to change the time format to a 24-hour clock format ...

Employ AJAX to dynamically refresh the page whenever a new row is inserted into the table

Currently, I am in the midst of learning AJAX because it is necessary for a project I am working on. The aim is to refresh a feed in real-time whenever a new row is added to a MYSQL table. While I have successfully achieved this using node.js, my client&ap ...