Error: data update to database failed due to technical issues

Struggling with updating data to MongoDB using Express. Despite receiving a status 200 response from my API, I can't seem to update the values in Mongoose when using Mongoskin.

var mongo = require('mongoskin');
var db = mongo.db(config.connectionString, {
    native_parser: true
});
var ObjectId = require('mongodb').ObjectID;
db.bind('users');
db.bind('dashboard')

function update(_id, userParam) {
    var deferred = Q.defer();

    for (var i = 0; i < Object.keys(userParam).length; i++) {
        var set = {

            file: userParam[i].file,
            result: userParam[i].result,
            user_id: userParam[i].user_id

        };
        db.dashboard.update({
                _id: mongo.helper.toObjectID(_id)
            }, {
                $set: set
            },
            function(err, doc) {
                if (err) deferred.reject(err);
                deferred.resolve();
            });
    };
    return deferred.promise;
}

This is how my API looks:

{
    "0": {
        "_id": "57396e49a6c36801024021a1",
        "file": "app_static/audio/SampleAudio_0.4mb.mp3",
        "result": "FM",
        "user_id": "57396ded0aef5ee405320dbe"
    },
    "1": {
        "_id": "57396e5ca6c36801024021a2",
        "file": "app_static/audio/SampleAudio_0.7mb.mp3",
        "user_id": "57396ded0aef5ee405320dbe"
    }
}

I'm utilizing a for loop to ensure the entire API is processed and pushed to MongoDB.

If you have any suggestions for an alternative way to push an entire JSON to MongoDB, please share them.

Your assistance is greatly appreciated!

Thank you in advance.

Answer №1

db.dashboard.update is a function that operates asynchronously (also known as non-blocking) and requires a callback as an argument.

You are invoking db.dashboard.update multiple times within a for loop, however, in the callback, you are either rejecting or resolving the same promise.

This implies that the then method of the returned promise will only be executed when the callback of the initial call to db.dashboard.update is triggered.

Subsequent update operations will not trigger your then function at all.

POTENTIAL SOLUTIONS:

1

Encapsulate your asynchronous code within an IIFE and invoke your deferred.resolve during the final iteration of the loop.

function update(_id, userParam) {

    var deferred = Q.defer();

    var length = Object.keys(userParam).length;

    for (var i = 0; i < length; i++) {
        var set = {

            file: userParam[i].file,
            result: userParam[i].result,
            user_id: userParam[i].user_id

        };

        (function(set, i) { // <------------------------- enclosing everything in an IIFE

            db.dashboard.update({
                    _id: mongo.helper.toObjectID(_id)
                }, {
                    $set: set
                },
                function(err, doc) {
                    if (err) {
                        deferred.reject(err);
                    } else if (length - 1 === i) { // <-- checking if this is the last iteration
                        deferred.resolve();
                    }
                });

        })(set, i); // <--------------------------------- sharing set and i with the IIFE scope
    };

    return deferred.promise;
}

2

Consider using async.map. This approach provides a more elegant solution.

function update(_id, userParam) {

    var deferred = Q.defer();

    /**
     * Array to store all sets
     */
    var arrayOfSets = [];

    /**
     * Convert key-value pairs in userParam to array elements and push into arrayOfSets
     */
    for (var i in userParam) {
        arrayOfSets.push({

            file: userParam[i].file,
            result: userParam[i].result,
            user_id: userParam[i].user_id

        });
    }

    /**
     * Execute async.map
     */
    async.map(arrayOfSets, function(item, callback) {

        db.dashboard.update({
                _id: mongo.helper.toObjectID(_id)
            }, {
                $set: item
            },
            function(err, doc) {
                if (err) {
                    callback(err, null);
                } else {
                    callback(null, doc);
                }
            });

    }, function(err, result) {

        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(result);
        }

    });

    return deferred.promise;

}

Remember, always enclose else statements within an if...else block!

function(err, doc) {
    if (err) {
        deferred.reject(err);
    } else { // always enclose in else!
        deferred.resolve();
    }
}

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

Error encountered: DOMException - Prevented a frame originating from "domain_name" from accessing a different origin frame

Utilizing the Mautic newsletter for my website has been a great experience. Here is the js code I've been using: /** This section should only be included once per page if manually copying **/ if (typeof MauticSDKLoaded == 'undefined') { ...

Monitoring the initiation and completion of web requests within the Ionic framework

Currently utilizing the ionic framework in conjunction with Angular JS. In need of assistance on how to monitor the initiation of a web request. To handle the completion of a request, I have created a directive with an onLoad attribute. Here is the exam ...

Guide to updating a value within a nested sub-array in MongoDB using pymongo

Data: { "_id" : ObjectId("50cda9741d41c81da6000002"), "template_name" : "common_MH", "role" : "MH", "options" : [ { "sections" : [ { "tpl_option_name" : "test321", ...

Tips for organizing extensive live data in MongoDB

Allow me to clarify the issue at hand. We receive real-time data of up to 0.2 million records per day. Some of these records hold special significance, with specific attributes that categorize them as such being stored in a reference collection. Let&apos ...

"Encountering issues with the construction of a Heroku application generated using the angular

After successfully building my app with sudo grunt build and serving it using sudo grunt serve:dist, I encountered an issue when trying to deploy to Heroku using yo angular-fullstack:heroku from the project root for the first time. The deployment process ...

Requiring a condition for each element in an array which is part of an object

Let's discuss a scenario where I have to decide whether to display a block based on a certain condition. Here is an example array structure: const data = [ { name: "item1" , values : [0,0,0,0,0]}, { name: "item2" , values : [0,0,0,0,0]}, { nam ...

Uploading base64 arrays from AngularJS to a Node.js server: Allowing Access-Control-Origin

My current challenge involves sending an array of base64 strings from my Client Side (AngularJs) to my NodeJs Server. However, I've encountered a peculiar situation. When I attempt to send an object containing the base64 data along with other properti ...

By incorporating JavaScript, clicking on an image will trigger a shift in the position of a different element

Just starting out with JavaScript and experimenting with creating an event where clicking on an image triggers the movement of another hidden image. The hidden image is positioned off-screen to the left, while there is a table of images in the center of th ...

Concealing the print option while utilizing PDFObject in conjunction with PDF.js

When displaying a file using pdf.js, I encountered issues with the print button and other functionalities. I was able to hide the buttons using CSS for Chrome, but not for Internet Explorer, where I had to resort to using JavaScript. While the JavaScript ...

conceal a division beneath a YouTube video frame upon clicking

I need to hide the 'div .blind' element when a YouTube video (inside 'div #player') is clicked. How can I achieve this? Here's an example: JS: ... var player; function onYouTubeIframeAPIReady() { player = new YT.Player('pl ...

Pass information between two forms using the Post method and Ajax communication

For my project, I attempted to retrieve data using the POST method in the processing file but encountered difficulties. I need to be able to receive the data through the POST method and display it on process.php. It's worth noting that my inputs are n ...

Regularly occurring significant updates across MongoDB, Lucene, and other platforms

Currently, I am in the process of designing a web application that possesses the following attributes: Contains millions of records Highly indexed/searchable using various criteria Incorporates a variable document schema Requires regular updates in block ...

The function inside the click() event will run once the click method for the element has been set

<!doctype html> <html> <head> <script src="jquery.js"></script> </head> <body> <script> function displayMessage1(){ $("#button").click(displayMessage2()); window.alert("dis ...

Retrieve information from Node.js using Express

I am working on a server with Node.js and using Express to create a web application. I have successfully implemented a function called rss_interrogDB that retrieves an array from a database. Now, I am trying to use this array to display a list on the HTML ...

"Customizable rectangular container with jagged edges created with Scalable Vector Graphics

Currently, I am undertaking a small project that involves creating a box with rough edges around some text. To achieve this effect, I am utilizing an SVG with unique edges similar to the design found at this link: (except mine is in SVG format). My goal ...

Conceal when dates align

In my events list, I have dates displayed and would like to hide any end dates that are the same as the start dates. For instance; <span class="start_date">Wed 23rd January</span> <span class="end_date">Wed 23rd January</span> I ...

Receiving a null value when using getElementById

I am attempting to read and display a text file, but the Chrome console is showing an error: caught TypeError: Cannot read property '0' of undefined FinanceDashBoard.html:22" I'm not sure where I am going wrong? The code I am using is: & ...

Accessing a nested value in MongoDB: A step-by-step guide

I am working on a document where I have a category object containing fields for category name, cost, and date. My task is to retrieve categories specifically from the year "2022". The console is currently showing "[]" output, but I want it to display categ ...

Using JavaScript, create a regular expression with variables that can be used to identify and match a specific section of

Struggling to apply a regex (with 1 variable) to compare against a HTML code page stored as text. The HTML code is separated into an array, with each element representing a snippet like the one below. Each element showcases details of fictional Houses (na ...

Error encountered: `TypeError: Unable to access undefined properties (specifically, '0') within the Simple React Project`

Currently in the process of learning React and working on a simple photo application. Encountering an issue: Collection.jsx:6 Uncaught TypeError: Cannot read properties of undefined (reading '0') Why is this happening? Everything was functioni ...