The database threw an error: "Duplicate key found in collection causing MongoError: E11000"

I'm currently in the process of updating an object within an array found in a document

    "state": [],
    "users": [{
        "ready": false,
        "_id": {
            "$oid": "5fb810c63af8b34180912014"
        },
        "user": {
            "$oid": "5f81eb91d537dc3baf443a84"
        },
        "calification": 0
    }, {
        "ready": false,
        "_id": {
            "$oid": "5fb810ca3af8b34180912015"
        },
        "user": {
            "$oid": "5fa6f98f15e96c1125b905a9"
        },
        "calification": 0
    }],
    "test": {
        "$oid": "5f986af2baa88b2d30760961"
    },
    "__v": 1
}

Here is the function I am using for this task:

updateUserState = async function(game_id,username){
    var user_id = '5fb7fae0c28f1d33a99b877e';
    await Game.findOneAndUpdate({_id: game_id, users: {$elemMatch: {user: user_id}}},
        {$set: { ready: true}}, 
        {'new': true, 'safe': true, 'upsert': true});
}

However, I encountered the following error:

(node:16768) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: myproject.games index: _id_ dup key: { _id: ObjectId('5fb810c63af8b34180912013') }

I am puzzled as to why it is specifying that the key is a duplicate

Answer №1

{updateOne: true, returnNew: true, validateRun: true}

Feel free to experiment with the code snippet provided

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

A guide on utilizing a mongo-query to compare two arrays and determine the set difference

UniqueUserDetails { "_id" : "5c23536f807caa1bec00e79b", "UID" : "1", "name" : "A", }, { "_id" : "5c23536f807caa1bec00e78b", "UID" : "2", "name" : "B", } UserItems { "_id" : "5c23536f807caa1bec00e79c", "UPID" : "100", ...

Invoking a Directive within another Directive

Feel free to check out this demo on Plunkr. I've set up a basic structure: <body ng-app="myApp"> <div ng-controller="myController"> <parent-directive></parent-directive> <child-directive></child-direc ...

How can I retrieve the class of the parent element by referencing the child id in jQuery?

I want to trigger an alert on click from the child id <th id="first"> to the table(parent) class. alert($(this).parent('tr').attr('class')); This code helped me to get the class of the <tr>. However, when I try to get the ...

Ways to effectively pair a radio button with a dropdown menu

function radioCheck() { document.getElementById("last").checked = "checked"; } <label> <input type="radio" name="Ppub" value="" checked="checked">All Dates </label> <br> <label> <input type="radio" id="last" name="Ppu ...

Navigating Angular with relative paths: A guide to locating resources

Here is the structure of my app: index.html main.ts app |--main.component.html |--main.component.ts |--app.module.ts |--note.png ... etc I am trying to include the note.png file in main.component.html which is located in the same folder. I have att ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

The process of setting up a carousel for tables using jQuery

I can successfully implement jquery for an image carousel, but now I need to find a way to create a sliding table format. Any assistance on this matter would be greatly appreciated. Here is the code I currently have: <ul> <li><a style= ...

Tool designed to analyze the timing of sub requests and methods in Node for benchmarking purposes

For my benchmarking and load testing needs, I initially utilized tools such as Apache Bench, Siege, and benchmark.js. However, these tools only provided me with the overall result or time taken from start to finish of the test. I am now seeking a tool or l ...

Create visual representations using a JSON structure that includes timestamps for various locations

I need to create a JavaScript graph based on a JSON dataset containing locations and timestamps. The data is structured like an array, and my goal is to visualize the time spent at each location with a comprehensive graph. ...

Catching the Selenium NoSuchElementError in JavaScript is impossible

Update: It's puzzling why this was marked as answered since the linked questions don't address the issue at hand and do not involve Javascript. My objective is to detect this error, rather than prevent it, given that methods like invisibilityOfEl ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

How to clear a particular select option in react-bootstrap

I am looking for a solution to clear the second select when the first one selects option B. The clearing should involve removing the value, disabling it, and setting the default option to Select.... import React, { useState } from "react"; import ...

Is there a way for me to retrieve the current value of a star rating when I click on it?

Looking for assistance with a ReactJS rating stars component that behaves oddly. The starting value is set to 5 stars, but each click on the stars seems to return the previous value rather than the current one. import React, {useState} from "react&quo ...

The error message 'Blob is undefined' pops up when trying to use react-media-recorder in an Astro project

I'm currently working on a project that involves Astro and React components, and I'm attempting to integrate react-media-recorder. The code I have is quite simple, just a React component placed within an Astro page: import { useReactMediaRecorde ...

Storing and Retrieving an Object Identifier in MongoDB (MEAN Stack)

I am currently learning the MEAN stack and encountering difficulties in correctly linking an ObjectId with MongoDB using JavaScript. Additionally, I am struggling to display the corresponding name associated with that ObjectId in my view. The main objecti ...

Having trouble retrieving data from a JSON response in a NodeJS environment

My current challenge involves checking the values returned from a query in JSON format. Although my code is functioning properly up until the condition statement, I discovered during debugging that the value I attempt to retrieve and compare from the JSON ...

Guide to triggering React Material-UI modal and filling it with data from an Ajax request when a button is clicked

Despite my efforts to find a similar question, I couldn't come across one. My apologies if I overlooked it. Currently, I am working on a React Material-UI project to develop a basic web application. Within this application, there is an XGrid that disp ...

How does gray-matter function in Node.js affect the matter within?

import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; const postsDirectory = path.join(process.cwd(), 'posts'); // ... ... ... // export function getPostData(id) { const fullPath = ...

Encountered a 'forEach' method error on the Node.js-Ejs-Mongojs tech stack

In my application's app.js file, I have a callback function named "tester" that retrieves all the content from the "locale" collection: tester = function(callback) { db.locale.find({}, function(err, locale) { callback( null, locale ) }); }; ...

javascript for each and every textarea

I am looking to apply my JavaScript code to all the Textarea elements on my page. $_PAGE->addJSOnLoad(" $('.textarea').each(function() { $(this).keyup(function() { var characterCount = $(this).val().length; var mes ...