Enhancing MEAN Stack Application by Updating Table Post Database Collection Modification

In my efforts to ensure that my table data remains synchronized with the database information, I have encountered an issue.

Whenever Data Changes:

    $scope.changeStatus = function($event,label,status){
    var target = $event.currentTarget;
    target = $(target).parents('tr').attr('id');
    $http({
        method: 'POST',
        url: '/update',
        params: {
            trgt : target,
            label : label,
            labelstatus : status,
            searchQuery : $scope.search  
        }
    })
    .success(function(data){
        console.log(data);
        $scope.events = data;
    })
    .error(
    function(error){
          console.log(error)
    });

}

Next:

app.post('/update', function(req,res){
    ImportCollection.findOne({ _id : req.query.trgt },function(err,doc){
        doc.label.label = req.query.labelname;
        doc.label.status = req.query.labelstatus;
        doc.save();
});

// UNTIL HERE EVERYTHING WORKS JUST FINE

if(req.query.searchQuery){
ImportCollection.find({$or:[
    {'localizedData.0.title' : {'$regex': req.query.searchQuery, $options: 'i' }},
    {'licensor.name' : {'$regex': req.query.searchQuery, $options: 'i'}}
    ]})
    .exec(function(err, imports){
        if(err) throw err
        res.json(imports)
        })
    } else{
        ImportCollection.find({},function(err, imports){
            if(err) throw err
            res.json(imports)
            })

    }
});

However, there is a delay in updating the table data after each request. For example, when changing from "Live" to "QA", the table still shows "Live". Only after changing it to "DENIED", does the table reflect the change to "QA". This inconsistency persists in the data updates.

Any suggestions or insights on how to resolve this issue?

Answer №1

Using the find() block as a callback function and passing it to the doc.save() method was the solution that worked perfectly in my case:

 doc.save(function(err){
          if (err) throw error

          var query = req.query.searchQuery;
          if(query) { 
              ImportCollection.find({$or:[
                     {'localizedData.0.title' : {'$regex': req.query.searchQuery, $options: 'i' }},
                     {'licensor.name' : {'$regex': req.query.searchQuery, $options: 'i'}}
                    ]}).exec(function(err, imports){
                  if(err) throw err
                  res.json(imports)
              });
          } else{
              ImportCollection.find({}).exec(function(err, imports){
                  if(err) throw err
                  res.json(imports)
              });
          }


      });

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

Issues with passing information from a child component to a parent component in a

Currently, I am developing a guessing game that involves questions and selection logic embedded in a component known as Questions. However, I am facing issues with App not being able to read the Questions code correctly. My objective is to have the state i ...

Is there a way to store JSON data in a constant variable using Node Fetch without encountering the error TypeError [ERR_INVALID_URL]: Invalid URL?

In my current NodeJS project, I am working on extracting data from a JSON file and then sending it to a constant variable in my app2.mjs. The goal is to organize this data into an array of objects and eventually save it into a database. However, when tryin ...

Issue with using @ symbol in src alias in vite/vue project causing malfunction

Recently, I set up a Vue3/TS project using the Vite CLI The configuration in my vite.config.ts is as follows: import vue from '@vitejs/plugin-vue' import { defineConfig } from 'vite' import path from 'path' export default de ...

Does React JS set initial value after re-rendering its state?

Every time the state is updated, the function is triggered once more (please correct me if I am mistaken). And since the initial line of the App function sets the state, the values of data and setData will not revert to their defaults. For instance, i ...

The error message "TypeError: Unable to access the 'get' property of an undefined vue js object" appeared

Struggling to grasp the concept of vue.js, I am currently navigating my way through understanding how to fetch or call an API. Setting up my index.html and app.js, along with the required packages in the node_modules, has been relatively smooth. However, ...

Error in zone: 140 - Property 'remove' is not readable

I'm brand new to kendo ui. I successfully set up a prototype in my fiddle with a working delete confirmation window. However, when I try to integrate it into my existing codebase, I encounter an error: Cannot read property 'remove' at the li ...

Update the content within a document and implement jQuery to make it clickable

Within my webpage, there is a random occurrence of the word -FORM-. I am looking to replace this word with another text that includes dashes for creating a clickable div. Despite having some code that successfully replaces the text, it lacks the function ...

Verify if a <select> element exists inside the main div

Is there a way for me to check if a <select> element is present within the parent div and display certain content based on its existence? Appreciate any assistance! ...

The issue with NGX-Bootstrap/Angular Pagination arises when attempting to adjust the maxSize input while the screen view (width) is being altered

Currently, I am utilizing the Pagination component from Valor Software (click here to access). I am interested in adjusting the maxSize input dynamically based on changes in screen width. For reference, please see this example: Click to view example. It ...

UI-router issue: UI view and links not functioning properly

Recently, I decided to implement ui-router for Angular in my project. After adding the following code snippet to my app module within the app.js file: angular .module("ngClassifieds", ['ngMaterial', 'ui.router']) .config(function($md ...

Error: string literal left incomplete with spaces only

I am attempting to run parameters from a JavaScript function, but I am encountering an issue with quotes when there is a white space present. This error specifically pertains to Mozilla: SyntaxError: unterminated string literal Below is the relevant p ...

Having trouble converting response.data to a string in ReactJS

import React, { Component } from 'react' import TaskOneServices from '../services/TaskOneServices' import circle from '../assets/icons/dry-clean.png' import tick from '../assets/icons/check-mark.png' async function ...

The animation isn't loading

I discovered a handy script that displays a waiting message when my form is submitted. I implemented jquery-ui to showcase this message in a dialog box, and it was successful. However, upon customizing the text and adding an animated gif background using C ...

Transforming RGB Decimal Color to HEX RGB Color in Three.js

Currently, I am facing a challenge in my task involving colors while working with three.js, a JavaScript library. In this particular task, I need to convert decimal color codes (e.g. 12615680) into formats like #FF0000 or 0xFF0000. I am seeking a JavaScr ...

Making modifications to and removing a single data entry from an entity

Currently, I am working on a project to develop a system that can handle the display, editing, and deletion of player and team information using Angular in conjunction with a RESTful API. So far, I have been able to successfully showcase all the data and p ...

What is the process for adding a custom header when making an ajax call in a datatable?

Currently, I am utilizing datatables and need to include a custom header for specific server-side requirements. Can anyone provide guidance on how to send a custom header when navigating to the next or previous pages using jQuery datatables? Additional ...

Numerous sessions activated upon initial page visit

Each time a user visits the site, I automatically assign them a session and store the corresponding data in a MongoDB collection named sessions. Additionally, a cookie is set to help identify returning users. This cookie allows me to retrieve the session w ...

AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user ...

getting TypeScript configured with webpack

I am currently using Typescript to develop a back-end API utilizing graphql and express. To manage the project development and building process, I have implemented webpack. As part of my setup, I am employing raw-loader in order to load graphql schemas an ...

What is the best way to compare JavaScript arrays with the same items but in a different order?

Within my product groups, each group is identified by a set of product_type_ids. I am looking for a way to match different groups based on their product_type_ids. The order of the ids may vary within the group, but as long as the sets of ids match, I cons ...