Unable to execute mongoose operation on database collection due to certain restrictions

Currently utilizing Mongoose for communication with MongoDB. Running into issues while attempting to execute certain operations.

The database contains a collection named USERS, characterized by the following schema:

{username: 'user1', id: 1, lastName: 'ln1' }
{username: 'user2', id: 0, lastName: 'ln2' }

The 'id' field can possess values of 0, 1, 2, or 3.

I am looking to add a new object based on the following conditions:

  • If the username already exists and has an id of 1, update the details.
  • If the username does not currently exist, create a new entry without verifying the id field.
  • If the username exists but has an id of 0, 2, or 3 (non-1 values), refrain from making any updates or adding the user to the collection, maintaining the existing user's data as they failed to be added to the database.

Your assistance is greatly appreciated.

Answer №1

Utilizing a promise library has been my approach, although callbacks can also be utilized.

Let's assume that the intention is to work on the User model.

User.findOne({username:"USERNAME"}).exec()
    .then((result)=>{
      if(result){
          if(result.id == 1){
         //update result object and then save it
           result.lastName="abc";
           result.save(); // this will update your result
            }else{
           console.log('failed to enter in the db.')  
           }
        }else{
          User(userObject).save(); // this will create a new entry
        }

})

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

Developing versatile form elements with Formik and the Yup library for React and Vite

I'm currently working on a React and Vite project where I'm trying to implement reusable form components using Formik and Yup, but I haven't been able to achieve it yet. I've created a component called <AppInputField/>, which is e ...

Connecting JavaScript and jQuery scripts

Help needed! I am a beginner in the world of jQuery and JS. Unfortunately, my JS/jQuery code is not running and I can't figure out why. Can someone please take a look at my HTML and guide me on what might be causing the issue? Do I need to add some ad ...

What is the correct way to serialize and deserialize an array of objects to and from JSON format?

I'm currently working on implementing a friends list feature that needs to be stored in a .json file using Kotlin/Java with libgdx. While Java is also an option for this project. The code I have written for (1) isn't functioning correctly, so ins ...

When faced with the scenario of having the hashtag in the href attribute and a browser's back button, it

Hello everyone, I've encountered an issue with the "back" action in my browser. When I click on a link, it takes me to a specific page due to a JavaScript function being called. However, when I hit the back button, it simply removes the "#" from the U ...

How can I ensure that Redux-saga waits for API calls to resolve instead of returning promises continuously? Is there a way to make "yield call" wait for API calls to complete?

Where I'm initiating the API request: function fetchCharacter(value){ return axios.get(`https://www.breakingbadapi.com/api/characters?name=${value}`) .then(res=>{ console.log(res.data) }) .cat ...

The ng-route feature seems to be malfunctioning and I am unable to identify the error, as no information is being displayed in the console

Here is the code in my boot.php file where I have set up the links <ul class="nav nav-pills nav-stacked"> <li role="presentation"><a href="#/valley">Valley</a></li> <li role="presentation"><a href="#/beach"> ...

Using Express and Node.js to display a page populated with information

On my webpage, I currently have a list of Teams displayed as clickable links. When a link for a specific Team is clicked, the Key associated with that Team is extracted and sent to the /team/:key route to retrieve the respective data. If the data retrieval ...

Verifying user authorization for Microphone access prior to triggering event in React application

I have created a React component featuring a microphone button that operates as follows: OnMouseDown => Initiates audio recording by the user OnMouseUp => Ceases audio recording To elaborate, while the button is pressed down, the user can continue ...

How can you retrieve nested JSON data in ReactJS by clicking the Search button?

I have attempted various methods to accomplish this task, such as How to read a nested JSON in React? Can't access nested JSON Objects in React My goal is to trigger an API query when the "Search" button is clicked. Currently, the API successfully q ...

Could someone assist me in crafting a C# mongo query that mirrors the functionality of an SQL query?

MongoDB Error: Unsupported filter: ({document}{FILEDATE} > {document}{SPLITDATE}). Query in SQL: SELECT * FROM CURRENT AS C WHERE C.FILEDATE > C.SPLITDATE C# code snippet: db.GetCollection<CollectionName>().AsQueryable() .Where(a => a. ...

Issues with CreateJS chained animations failing to reach their intended target positions

Currently, I am tackling a project that involves using Three.js and CreateJS. However, I have encountered an issue with the animations when trying to move the same object multiple times. The initial animation fails to reach the target position, causing sub ...

Unable to establish connection with Uploadthing due to a timeout error

I am facing timeout errors while setting up the upload feature. app/api/uploadthing/core.ts import { createUploadthing, type FileRouter } from "uploadthing/next"; import { auth } from "@clerk/nextjs"; const handleAuth = () => { c ...

What is the reason for this basic callback running before the setTimeout function?

Interesting behavior is observed in this code, where 'output 2' is logged before 'output 1' due to the setTimeout function. const func1 = () => { setTimeout(() => { console.log('output 1'); }, 3000); }; con ...

Directive in Angular for customer management with filtering and sorting functionality

I am struggling to organize the JSON object by userType using ng-repeat. While I have successfully retrieved and displayed the data, my ISSUE is that I need to sort and display two different tables for the following list: One for MARRIED individuals and an ...

Issue encountered while trying to utilize the reset function of the FormGroup with the angular2-tinymce plugin

I utilized the FormGroup feature to construct my form, and I required a textarea component. I decided to use the angular2-tinymce library/package to create the form. Here is my HTML template: <form (submit)="submitCallLog($event)" [formGroup]="callLo ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

What is the best way to utilize d3.domain for extracting both d3.min and d3.max values from various columns within a JSON dataset?

I have a JSON file that contains data from different years for "male," "female," and "both" categories. I want to set the minimum value in my domain to be the lowest value across all three columns and do the same for the maximum value. Is there a way for ...

I am in search of a JavaScript or jQuery plugin for an HTML slider with a unique range functionality

I've been searching online but couldn't find a slider like the one shown in the attachment. Can anyone help? Is there a way to create this specific slider or is there an existing plugin or library for it? Please refer to the image below :https:/ ...

Determine the originating page in Next.js that leads to the current page

Imagine a scenario with three pages: A, B, and C. In this setup, it is possible to navigate from page A to C, as well as from page B to C. However, the displayed content on page C will vary depending on the origin page of the navigation. I am curious to ...

Is there any HTML code that is able to implement a currency format identical to the one we've customized in Google Sheets/Google Apps Script

I am currently working with a Google Sheet table that consists of 2 columns. The second column contains charges which can vary based on user input through a Google Form and are summed up using GAS. To view an example, click here. The data from this Googl ...