What is the best way to fix the UnhandledPromiseRejectionWarning: ValidationError issue?

After trying multiple solutions from Stackoverflow related to mongoose errors, I am still facing a problem with the code below. I believe the issue lies elsewhere, but I am unable to pinpoint it.

This file is connected to other files as well.

.finally catch (it resolves part of the error)

const assert = require('assert');
const User = require('../src/users');

describe('Testing virtualType', () => {

    it("Ensuring that the virtualType correctly returns the number of books owned by the user", (done) => {
        const user1 = new User({
            userName: 'Robin',
            shopslist: [{ shopName: 'Lord of the Rings' }, { articleName: 'Grapes of Wrath' }]
        });

        user1.save()
            .then(() => User.findOne({ userName: 'Robin' }))
            .then((User) => {
                assert(user1.countShops.length === 2);
            })
            .finally(done);

    });
});

The terminal shows:

(node:19900) UnhandledPromiseRejectionWarning: ValidationError: user validation failed: shopslist.0.articleName: ArticleName is required, shopslist.1.shopName: ShopName is required
    at new ValidationError 
    at process._tickCallback (internal/process/next_tick.js:61:11)
(node:19900) 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: 9) 

Answer №1

UnresolvedPromiseWarning - Make sure to properly deal with errors by implementing resolve() and reject() when working with promises returned from the .save() method for a specific instance of User. You can follow this pattern:

 const newUser = new User(...);

 newUser.save()
.then(done =>{ //Work goes here })
.catch(error =>{ 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

Creating a dialog box that effectively blocks user interaction

Is it possible to implement a blocking dialog box with JavaScript/JQuery/Ajax? I've been working with the JQuery UI dialog box, but using it asynchronously with callback functions has made it more complicated than expected. For example: ans1 = confi ...

Including material-ui/core/Table produces a data error before it has even been connected

My Initial Redux Saga Setup In my Redux Saga code, I have a generator function that fetches data from a mock API: function* fetchPickingScans({orderReference}){ try{ const response = yield call( scanningMockApi.getPickingScans, orderReference ...

Guide to selecting a specific year on a calendar using Selenium with JavaScript

While attempting to create a Selenium test using JavaScript, I encountered an issue with filling in calendar data through a dropdown menu: const {Builder, By, Key} = require('selenium-webdriver') const test2 = async () => { let driver = awa ...

Troubleshooting issue with ng-value in Ionic framework and AngularJS not

I'm facing an issue with an ng-value assigned to an input field. I want to pass the userID to the input field so it can be submitted when the form is clicked. Below is the HTML code snippet: <div ng-repeat="chats in chat"> <form ng-su ...

Error message: "Missing attribute X in the GraphQL result for Vue"

Recently started using vue as a frontend with vue 2.3.11 and Django 3 as the backend, connecting them through Apollo via vue-cli. In my backend, I have a table named documents which consists of only a name and an id field. I am fetching this data from the ...

What is the best way to define the active <li> tab using JQuery?

Initially, my HTML code includes a set of <li> elements that I want to dynamically add to the existing <ul>. <ul class="tabs" id="modal_addquestion_ul"> <li class="tab-link current" data-tab="multipleChoice">Multiple Choice< ...

MongoDB failing to store model information

As I dive into practicing with APIs to hone my skills in creating models and routes, I find myself stuck on getting my initial route to successfully save data to my MongoDB database. When testing with Postman, I encounter the following error: { "message" ...

The array.slice() method fails to work properly when I try to start it from any index other than 0

I am currently working with an array called $scope.results which contains 8 objects. I have also created a custom simple pagination and a function called selectAll() that I'm trying to get to work together. Please refrain from suggesting the use of b ...

Issue encountered while running Java scripts in Selenium with JMeter due to method invocation error

When attempting to run JavaScript in my Selenium code, I encountered the following error: Error: Response message: javax.script.ScriptException: Sourced file: inline evaluation of: import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; impo ...

Error message: NGINX combined with Express.js and socket.io, page not found

I currently have a node/express.js/socket.io application set up on an Ubuntu Server running on port 3002. I've made sure to open all ports on the machine for accessibility. When accessing the app directly at 11.111.111.1:3002/, everything runs smooth ...

Retrieving document attributes from a Mongoose Model with the help of Typescript

Incorporating Typescript with Mongoose, my aim is to retrieve properties from a Model. Taking the illustrated UserModel as an example import mongoose, { Schema } from 'mongoose'; const userSchema: Schema = new mongoose.Schema({ _id: mongoos ...

What is the best way to send multiple parameter values from jQuery to a Laravel controller?

I am facing an issue with my code where I don't understand how to send multiple parameters from jQuery to the controller. Below is the route: Route::get('/listcdix/{id}/detail/{asnumber}', ['as' => 'remindHelper', & ...

Angular 8 allows for dynamic updates as users provide input and make selections with check marks

When using Angular 8, if a user inputs "$10" and then clicks on it (using the OnClick event), the box below should be updated with the user input and the entire box should be selected like the example shown in the picture. I would greatly appreciate any t ...

What could be causing the inability to access the path variable within an IIFE?

After experimenting with the code, I discovered an interesting observation. When declaring const path = require('path') outside of the IIFE function, it is inaccessible within the function. However, when moving this declaration inside the functio ...

What may be causing a configuration problem with the USB binding in Electron?

I am encountering difficulties with installing USB modules in my electron app. Every time I attempt to install electron and its dependencies, I encounter the issues outlined below. Can someone please assist me in resolving this? If anyone has faced a simi ...

The sorting feature in Angular Material seems to be causing an issue as it is unable to define the property 'sort'

Recently, I encountered an issue with sorting columns in an Angular 8 application that utilizes Angular Material. In my quest to find a solution, I searched various resources including Google and online courses. I made some modifications to the TypeScrip ...

A pair of dropdowns with a single onchange event

Hey there! I'm looking to make my ajax function work only when both dropdown menus have values selected. And I'm wondering how to pass the data from both dropdowns. Here's what I have so far: SCRIPT <script> function getState(val) { ...

emphasizing the specific text being searched for within the page

Looking for a solution to search values and highlight matching text words on a page? Let me help you with that. $(function() { var tabLinks = $('.nav > li'), tabsContent = $('.tab-content > div'), ...

Vitejs is currently loading the entire bundle size instead of just the specific selected files

While working with Vue 3 and Vite, I came across an issue that seems quite strange. The Oh Vue Icons library is loading a massive 108 MB of bundle size, which significantly slows down the loading time even in ViteJS. Here's how my setup looks like: im ...

Tips for effectively structuring material-ui Grid in rows

I am currently using the material-ui framework to create a form. Utilizing the Grid system, I want to achieve the following layout: <Grid container> <Grid item xs={4} /> <Grid item xs={4} /> <Grid item xs={4} /> </Gr ...