Updating a Mongoose document without overwriting existing values using FindOneAndUpdate

I have the following schema:

{
        guildId: {
            type: String,
            required: true,
            unique: true
        },
        systems:{
            reactChat:{
                type: Array,
                required: true,
                default: []
            },
            notification:{
                tiktok:{
                    user:{
                        type: String
                    },
                    endCooldown: {
                        type: String,
                        default: '0'
                    }
                }
            }
        }

Now, I am trying to update the value of endCooldown in systems > notifications > tiktok using findOneAndUpdate. However, when I attempt this, it ends up resetting all values, including user. Below is the code I am currently using:

GuildSchema.findOneAndUpdate({guildId: id}, {
    systems:{
        notification:{
            tiktok:{
                endCooldown: String(Date.now() + 86400000) //24h
            }
            
        }
        
    }
}, () => {})

Is there a way to only modify the endCooldown value without affecting other fields?

Answer №1

When analyzing your original update, you are essentially executing the following operation...

{
op: 'command',
ns: 'nodetest.Things',
command: {
  findAndModify: 'Things',
  query: { guildId: 'GOPd3ccG1f' },
  remove: false,
  new: false,
  upsert: false,
  fields: {},
  update: {
    '$set': { systems: { notification: { tiktok: [Object] } } }
  },
  lsid: { id: UUID("f4462722-1970-43c5-b2e1-b1cc5e38e9d0") },
  txnNumber: Long("2"),
  '$clusterTime': {
    clusterTime: Timestamp(2, 1630100100),
    signature: {
      hash: Binary(Buffer.from("005ff0e9abe7f7386825f291dfdf769ae050f08a", "hex"), 0),
      keyId: Long("6967052092213035012")
    }
  },
  '$db': 'nodetest'
},
keysExamined: 1,
docsExamined: 1,
nMatched: 1,
nModified: 1,
nUpserted: 0,
numYield: 0,
queryHash: '6D0EBC2A',
planCacheKey: '479D3C98',
locks: {
  ParallelBatchWriterMode: { acquireCount: { r: Long("2") } },
  ReplicationStateTransition: { acquireCount: { w: Long("3") } },
  Global: { acquireCount: { w: Long("2") } },
  Database: { acquireCount: { w: Long("2") } },
  Collection: { acquireCount: { w: Long("2") } },
  Mutex: { acquireCount: { r: Long("2") } }
},
flowControl: { acquireCount: Long("1"), timeAcquiringMicros: Long("1") },
readConcern: { level: 'local', provenance: 'implicitDefault' },
writeConcern: { w: 'majority', wtimeout: 0, provenance: 'implicitDefault' },
responseLength: 409,
protocol: 'op_msg',
millis: 57,
planSummary: 'IXSCAN { guildId: 1 }',
execStats: {
  stage: 'UPDATE',
  nReturned: 1,
  executionTimeMillisEstimate: 0,
  works: 1,
  advanced: 1,
  needTime: 0,
  needYield: 0,
  saveState: 0,
  restoreState: 0,
  isEOF: 1,
  nMatched: 1,
  nWouldModify: 1,
  nWouldUpsert: 0,
  inputStage: {
    stage: 'FETCH',
    nReturned: 1,
    executionTimeMillisEstimate: 0,
    works: 1,
    advanced: 1,
    needTime: 0,
    needYield: 0,
    saveState: 1,
    restoreState: 1,
    isEOF: 0,
    docsExamined: 1,
    alreadyHasObj: 0,
    inputStage: {
      stage: 'IXSCAN',
      nReturned: 1,
      executionTimeMillisEstimate: 0,
      works: 1,
      advanced: 1,
      needTime: 0,
      needYield: 0,
      saveState: 1,
      restoreState: 1,
      isEOF: 0,
      keyPattern: { guildId: 1 },
      indexName: 'guildId_1',
      isMultiKey: false,
      multiKeyPaths: { guildId: [] },
      isUnique: true,
      isSparse: false,
      isPartial: false,
      indexVersion: 2,
      direction: 'forward',
      indexBounds: { guildId: [ '["GOPd3ccG1f", "GOPd3ccG1f"]' ] },
      keysExamined: 1,
      seeks: 1,
      dupsTested: 0,
      dupsDropped: 0
    }
  }
},
ts: ISODate("2021-08-27T21:35:00.994Z"),
client: '127.0.0.1',
allUsers: [ { user: 'barry', db: 'admin' } ],
user: 'barry@admin'
}

This approach is updating the systems.notification.tiktok object with a new object, not just the endCooldown field. If you wish to specifically modify only the endCooldown field, you should provide a targeted update like this...

GuildSchema.findOneAndUpdate({guildId: id}, { "$set": { "systems.notification.tiktok.endCooldown": String(Date.now() + 86400000)}}, () => {});

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

Extremely sluggish updating efficiency

As I parse through a CSV file, I aim to verify if the corresponding entry exists in the database for each row. If it does exist, I want to update it; if it doesn't, I want to create a new entry. The process seems to be sluggish, averaging only around ...

Removing an event from Fullcalendar

With the help of a post on StackOverflow, I managed to modify my select: method to prevent users from adding an event on a date before NOW. However, there is a drawback. When a user clicks on an empty time slot and the system displays an alert message, th ...

Discover how to obtain an access token using Yelp API V3 with JavaScript

Currently in the process of learning how to utilize this system, however there appears to be an issue with my code. $.ajax({ dataType: "POST", url: "https://api.yelp.com/oauth2/token", grant_type: "client_credentials", client_i ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

Is it advisable to utilize my DBClientConnection as a global variable in my program?

Windows 7 SP1 MSVS 2010 MongoDB 2.2.0 Qt 4.8.4 In my single-threaded application, I have always been passing the DBClientConnection as a reference argument to functions that need access to MongoDB. But now I wonder if it would be better to use a glo ...

"Implementing the Three.js OBJloader feature with the enhanced functionality of

I'm looking to create a simple 3D model viewer with rotation capabilities, but I've run into an issue. When I add OrbitControls to my code, the page just shows up as blank: controls = new THREE.OrbitControls( camera ); controls.addEventListener( ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

Personalizing the arrow positioning of the Angular8 date picker (both top and bottom arrow)

I am interested in enhancing the design of the Angular 8 date picker by adding top and bottom arrows instead of the default left and right arrows. Can someone guide me on how to customize it? Check out the Angular 8 date picker here ...

Display an image when the link is hovered over within a table

I'm looking for a way to display a scanned receipt image when hovering over a link within a table. I've written some code but it's not working as expected. Can anyone help me figure out what's wrong? Here is the current state of my cod ...

Enhancing a React Native application with Context Provider

I've been following a tutorial on handling authentication in a React Native app using React's Context. The tutorial includes a simple guide and provides full working source code. The tutorial uses stateful components for views and handles routin ...

Failure to give an error message occurred during a POST request on Parse.com and ExpressJS platform

I'm facing an issue where a POST request I send fails with error code 500 and there is nothing showing up in my server side error log. It seems like the cloud method may be missing. What's interesting is that the same POST request works fine wit ...

Developing a modal with various hyperlinks

I'm currently working on a website that features multiple news articles, each linking to a separate page. Is it possible to use modal windows to have the articles pop up on the same page instead of opening in a new window? If so, I would greatly appre ...

Icons in Semantic-UI: Facing Difficulty in Accessing ("CORS Request Not HTTP"

Here's an example I'm working on: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Understanding - Main</title> <link rel="stylesheet" type="text/css" href="../semantic/dist/semanti ...

Choose the offspring of an element using jQuery

Currently, I have a function set up to open a modal dialog and populate it with information from the 'dblclicked' node: $(function(){ $(".delete").live('dblclick', function () { var id = $(this).attr('id'); ...

Combining multiple jQuery selector objects into one jQuery object

How can I merge two jQuery selectors into one jQuery object? I attempted to use $("#selector","#selector"), but it didn't work and just returned blank. Are there any built-in methods that can help me accomplish this? Is there a way to do it like thi ...

Referencing a variable within a string: Discord.js Hyperlink

Essentially, when attempting to use a discord hyperlink, I found that breaking the string to add a variable does not work as expected. I have tried calling it using $ and {} but it still doesn't work. .addField('Shortcuts', $'[Profil ...

The validation of pre-filled input fields in Angular Material dialogs is not working as expected

I am encountering an issue with a mat-dialog that opens through an edit button within a (mat-)table. Upon opening the dialog, data is passed to populate certain input fields. One of these inputs has validation requiring that it cannot be left empty. The ...

Saving the Auth0 user object in React Context for Typescript in a Next.js environment

I am working on integrating Auth0 user authentication into my React application using the useUser hook and the context API. My goal is to access the user object globally throughout the app by storing it in the userContext.tsx file: import { createContext, ...

Adding HTML elements to a button using an array: a step-by-step guide

In the process of developing a web application feature using JavaScript, I have come up with a simple plan: Place a button in the bottom left corner. The button should only become visible after scrolling begins. Upon clicking the button, a new window wil ...

The ConsoleCapture does not capture every console error for Sentry

Running into an issue capturing console errors with Sentry in a Next.js app. The problem arises from an error within a library that is inaccessible to us, specifically related to WebSocket "WebSocket is already in CLOSING or CLOSED state" This error is c ...