Experiencing issues transferring a file to a different folder using mongoose

Here is the code snippet I am currently using to locate the document that needs to be duplicated to another collection:

public updateConfigWithType(req: Request, res: Response) {
  configs.findOne({'companyInfo.uniquecompanyid': req.params.id}, function(err, config){
      if (err) {
        return res.send(err);
      }
      let swap = new (oldConfigs.model('oldConfigs'))(config)
      swap.save()

      config.parserConfig = req.body;

      config.save(err => {
        if (err) return res.send(err);
          res.json({ data: config });
      });
  });
}


The error message being displayed is:
 (node:65757) UnhandledPromiseRejectionWarning: DocumentNotFoundError: No document found for query "{ _id: {} }"
 (node:65757) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
10:34:34 AM web.1 |  (node:65757) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I am uncertain on how to address these issues. Can someone please explain what I am overlooking here?

Answer №1

Two errors are intertwined here. It seems that the root of the problem lies within the swap.save() function. In mongoose, when no callback is provided as an argument, the method returns a Promise.

Be sure to thoroughly inspect the config object being passed into

let swap = new (oldConfigs.model('oldConfigs'))(config)
as this seems to be triggering the error.

The second error message is occurring because the promise error is not being caught. You could try something along the lines of:

swap.save().catch(console.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

Is there a way to specifically call the last promise in a loop?

I'm new to promises and could use some help. I have a situation where promises are resolving randomly, how can I ensure that the last promise in the loop is resolved after the full loop executes? For example, if this.selectedValues has 4 values, som ...

Obtaining the identifier of a generic type parameter in Typescript

Is there a method in TypeScript to retrieve the name of a generic type parameter? Consider the following method: getName<T>(): string { .... implement using some operator or technique } You can use it like this: class MyClass{ } getName< ...

Looking for the most effective method to establish a connection between OracleDB and SQLite using node.js?

Recently, I have embarked on a small project that has introduced me to the world of node.js, oracleDB, and sqlite. While these technologies are new to me, I have successfully implemented an oracleDB connection to fetch data from tables. However, I also hav ...

Connect to a particular Mongoose model query

In my invoice.js file, I have a self-contained model. Here is the code: 'use strict'; // load the necessary modules var mongoose = require('mongoose'); var auth_filter = require('../../auth/acl/lib/queryhook'); var invoice_d ...

Modifying the form-data key for file uploads in ng2-file-upload

I have implemented the following code for file upload in Angular 2+: upload() { let inputEl: HTMLInputElement = this.inputEl.nativeElement; let fileCount: number = inputEl.files.length; let formData = new FormData(); if (fileCount > 0) { // a f ...

Include a conditional statement in ng keypress

When a user types a specific value into a text input, I want to display a specific div. This is what my template looks like: <input type="text" id="jobTitle" (click)="autoCompleteClick()" (keypress)="autoCompleteKeypress()" name="autocomplete" place ...

HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template. new HtmlWebpackPlugin({ template: 'client/index.tpl.html', inject: 'body', filename: 'index.html' ...

Differences between urlencoded and form-data in Node.js

Can anyone suggest a fast method to distinguish between passing urlencoded data and form-data (multiparty) data in Node.JS? ...

Tips for achieving equivalent value from two separate arrays with the help of Lodash

I have two separate JSON array objects provided below. My goal is to extract the matching "stdname" value from the "stdcontinfo" JSON array and append it to the respective element in the "stdJson" JSON array. Is there anyone who can assist me in resolving ...

The importation of TypeScript source modules is not compiled accurately in the distribution folder

Currently, I am working on a REST API in TypeScript with the following structure: ├── dist │ ├── index.js │ ├── library.js ├── src │ ├── index.ts │ ├── library.ts ├── node_modules ├── package. ...

Triggering actionsheet button clicks in Ionic 3

I need assistance with adding buttonClick functionality to actionSheet buttons in ionic 3. When a button is clicked, I want to open a modal (custom alert). Below is the code snippet: openActionSheet() { console.log('opening'); le ...

Encountering an incorrect entry in the Mongo database while attempting to modify an entry

I am currently working on a project using Node.js with Express and MongoDB. The goal is to search for and update an entry (referred to as an "event") in the database based on its unique id. The id is passed in the request body as tempEventInfoForEdit, whic ...

Saving numerous model records within a single POST endpoint using Mongoose, Express, and Nodejs

My Search model and Result model have a one-to-many relationship. When the user performs a search, selects helpful results, and clicks on a save button, an app.post() request is triggered. This request should save an instance of the Search along with one o ...

Is it possible to modify a dependency import based on the specific request?

How can I switch between test mode and live mode using Stripe's SDK based on a query parameter in my internal form service for collecting payments? For example, consider this route: router.post("/:formId", function(req, res, next) { let isTest ...

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

MongooseError: Timeout occurred after 10000ms while attempting to buffer the operation `users.findOne()` in a Next.js application

Encountering the "MongooseError: Operation users.findOne() Buffering Timed Out After 10000ms" error in my Next.js app while using Mongoose (^8.2.2) to connect to MongoDB. Using Next.js version 14+ Troubleshooting Steps: 1. Checked MongoDB connection str ...

Stopping XSS Attacks in Express.js by Disabling Script Execution from POST Requests

Just starting to learn ExpressJs. I have a query regarding executing posted javascript app.get('/nothing/:code', function(req, res) { var code = req.params.code; res.send(code) }); When I POST a javascript tag, it ends up getting execut ...

Express-fileupload making it possible to upload files

I am having some trouble using express-fileupload to upload a file. Despite my efforts, I have not been successful in making it work properly. Although I can technically 'upload' the file (which is an image in this case) and see it displayed with ...

Do you need assistance with downloading files and disconnecting from clients?

When looking at the code snippet below: async function (req, res, next) { const fd = await fs.open("myfile.txt") fs.createReadStream(null, { fd, autoClose: false }) .on('error', next) .on('end', () => fs.close(fd)) . ...

"Embracing Node's Passport for Inviting Users

I'm currently developing a collaborative application that requires an invitation-only user registration process controlled by the admin. I explored Passport but haven't found a built-in feature for implementing an "invitation strategy" like Devis ...