What could be causing data to be saved twice when using a mongoose callback function?

Recently, I've been intrigued by the behavior of adding a callback to the mongoose findOneAndUpdate function and how it leads to saving data twice in the database.

public async addPersonAsFavorite(userId: string, friendId: string) {
    if (!await this.isPersonAlreadyFriend(userId, friendId)) {
      const friendList = FriendsList.findOneAndUpdate(
        { _id: userId },
        { $push: { friendsList: friendId } },
        { upsert: true, new: true },
        (err, data) => {
         if (err) console.error(err);
         return data;
        }
      );
      return friendList;
    }}

  public async isPersonAlreadyFriend(userId: string, friendId: string) {
    let isFriendFound = false;
    await FriendsList.findById(userId, (err, data) => {
      if (data) {
        console.log(data.friendsList);
      }
      if (err) console.error(err);
      if (data && data.friendsList.indexOf(friendId) > -1) {
        isFriendFound = true;
        console.log('already friend');
      } else {
        console.log('not friend');
        isFriendFound = false;
      }
    })
    return isFriendFound;
  }

Upon removal of the callback function, the data is saved only once.

EDIT: Additionally, after observing the second piece of code and encountering a new question. It was noticed that when multiple attempts are made to add a friend quickly, duplication occurs as the system initiates the process before the previous operation completes its check, leading to multiple entries being added unintentionally.

How can the system be configured to ensure completion of the DB write operation before allowing the function to be triggered again?

Answer №1

It seems like the issue may lie in the isPersonAlreadyFriend method, as you are attempting to call it using async await but then passing a callback, which prevents the method from returning a promise. To properly utilize promises with mongodb, you should consider implementing it in the following manner:

public async isPersonAlreadyFriend(userId: string, friendId: string) {
    let isFriendFound = false;
    const data = await FriendsList.findById(userId);
    if (data) {
      console.log(data.friendsList);
    }
    if (data && data.friendsList.indexOf(friendId) > -1) {
      isFriendFound = true;
      console.log('already friend');
    } else {
      console.log('not friend');
      isFriendFound = false;
    }
    return isFriendFound;
  }

Give this approach a try and inform me if it resolves the issue for you.

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

What is the best way to load my CSS file using express.static?

How do I properly load my CSS file using express.static in Node.js? I have attempted various methods to link my stylesheet to my HTML file through Express, and I'm also interested in learning how to include images, JavaScript, and other assets to crea ...

Steps to update XmlHttpRequest URL during image upload

I am currently facing an issue with updating images on my website. When I try to update an image, it redirects to the wrong URL instead of the intended one. The form is set to post data to this URL: POST http://127.0.0.1/mgt/upload/processImage/foodImage ...

Unintentional GET request triggered by Axios baseURL

I have encountered a strange issue where defining axios.defaults.baseURL = baseUrl; results in an unexpected GET request right after initializing my Vue app. Any assistance would be greatly appreciated! Below are images showing the code and network reques ...

What is the best way to eliminate duplicate values within a v-for array?

To eliminate duplicate values, I wrote the following code: vue <div class="col-md-6" style="float: left"> <ul class="list-group"> <li class="list-group-item" :class="{ active: ind ...

Three.js Ellipse Curve Rotation

Purpose My goal is to create an EllipseCurve () where a camera will move. The Approach I Took to Achieve the Goal Below is the code snippet for creating the ellipse: var curve = new THREE.EllipseCurve( 0, 0, 1, 1, 0, 2 * Math.PI, false, ...

Text that is curving around a D3.js pie chart

I am currently working on creating a 3D-Js chart and I would like the pie text to wrap around the pie itself. This is the exact effect that I am trying to achieve: https://i.sstatic.net/YOLdo.png I am facing two main issues: I am currently printi ...

Failure to specify the variable type can lead to the creation of automatic global variables

Recently, I stumbled upon this http://www.w3schools.com/js/js_scope.asp page which introduced me to the concept of "Automatic Global variables". Here is an example of how it works: // You can use carName variable here function myFunction() { carName ...

The jqGrid is not showing the AJAX JSON data as expected

Currently, I am exploring jqgrid and trying to figure out how to display data in another jqgrid when clicking on a specific colmodel. The retrieved data from the server goes through a function and reaches the grid, but no information is displayed without a ...

Utilizing a middleware router for a subdirectory route in Express with Node.js

I am looking to implement a middleware specifically for the /doc path in order to serve static files and include basic authentication. However, when attempting to access /doc, I encounter a "cannot get /doc" error. Any suggestions or ideas on how to reso ...

Effortless Scrollspy with a custom Navigation Component, no Bootstrap needed

In my Table of Contents, identified as #TableOfContents, each href points to either an h2 or h3 tag. The issue I'm facing is that when the heading (h2 or h3) is observed by the intersection observer, the corresponding link in #TableOfContents is high ...

What changes can be made to the HTML structure to ensure that two form tags function separately?

Hey there! I'm currently tackling a web project that involves incorporating two form tags on one page, each with its own distinct purpose. Nevertheless, it appears that the inner form tag isn't behaving as it should. My suspicion is that this iss ...

Issues with Nuxtjs routing on Netlify

I currently have a NuxtJs (Vue) application deployed on Netlify. The issue I am facing is that when I redirect to other pages, the URL ends up concatenating the last page and the next page. For example, if the current page URL is https://page-example/regi ...

Tips for speeding up the response time of MongoDB and Node.js communication

I am currently working with a blog schema that includes fields such as title, topic, body, and author. I have a function that retrieves all the blogs stored in this document by using Blog.find(). However, I am facing an issue where the size of the body p ...

Issue with BlobUrl not functioning properly when included as the source in an audio tag

I need help with playing an audio file on click. I tried to implement it but for some reason, it's not working as expected. The response from the server is in binary format, which I decoded using base64_decode(responseFromServer); On the frontend (Vu ...

Discovering the process of mapping transitions in MUI

I'm struggling with mapping my products in mui and placing each one in Grow. However, I keep getting this error message: "Warning: Failed prop type: Invalid prop children of type array supplied to ForwardRef(Grow), expect a single ReactElement". Can a ...

Tips for retrieving all results without any parameters specified in the request URL

When I make the request to http://localhost:3000/getAll?warranty=1&model=M4, it displays all details with warranty=1 and model=M4. However, if I request http://localhost:3000/getAll?warranty=1, it shows no results. Below is my request router: router ...

Issue with the Styled Components Color Picker display

For the past 6 months, I have been using VSCode with React and Styled Components without any issues. However, recently I encountered a problem where the color picker would not show up when using CSS properties related to color. Usually, a quick reload or r ...

Substitute all items identified by a particular tag with a component

Is it possible to replace elements with React? I am interested in replacing all elements with a specific tag with an input field when an event like clicking an 'edit' button occurs. I have experience doing this with jQuery, but I would prefer us ...

Tips for iterating through an array of images and displaying them in a React component

I am working on a project in my react app where I have 5 images that I want to cycle through indefinitely. The goal is to create an animation where a light bar appears to be constantly moving. https://i.sstatic.net/8tdfV.png The shifting dot in each imag ...

The switch case functionality refuses to change when I interact with the user interface

Can someone please help me troubleshoot? I'm not receiving any errors in the Chrome console. HTML <div class="wrapper"> <i id="repeat" class="fas fa-stop-circle"></i> </div> Javascript const wrap ...