"Trouble with findOneAndUpdate function failing to update the

Struggling to update a document in my mongoose server using findOneAndUpdate. I've set it up as a PUT request with the following definition:

public updateConfigWithType(req: Request, res: Response) {
    configs.findOneAndUpdate({'companyInfo.uniquecompanyid': req.params.id}, { $set: { companyName: "ITSWORKING" }} ,(err,doc) => {
        if (err) {
            res.send(err);
        }else {
          res.json({
              message: 'Succesfully updated this item'
          });
        }
    })
}

The PUT request URL is formatted like this:

http://localhost:3000/parserConfig/123123wfdwedfwfwefwef

Here's a snippet of the JSON data from my mongoose documents:

{
    "_id": {
        "$oid": "5bbf27ad4cf8a6be65ea6257"
    },
    "companyInfo": {
        "companyName": "example",
        "hashKey": "sdfsdf",
        "hashFunction": "sdfsdf",
        "uniquecompanyid": "123123wfdwedfwfwefwef"
    },
    "version": "1",
    "__v": 0,
    "parserConfig": {
        "id": {
            "fieldName": "key",
            "path": "key"
    },

The goal is to retrieve the correct document by its uniquecompnayid in the URL and specifically update the parserConfig field with the content of req.body. At the moment, sending a PUT request returns:

{"message":"Succesfully updated this item"}

However, no actual changes are made. What could be causing this issue?

Update

In an attempt to troubleshoot, I modified the code like so:

public updateConfigWithType(req: Request, res: Response) {
  var query = {'companyInfo.uniquecompanyid':req.params.id};
  configs.findOneAndUpdate(query, {$set:{'companyInfo.uniquecompanyid':"heheheheh"}}, {new:true}, function(err, doc){
      if (err) {
        return res.send(err);
      }
      return res.send(doc);
  });
}

Despite these adjustments, Postman still displays the old document without any updates.

UPDATE after spyros request

10:26:34 PM web.1 |  Mongoose: configs.findOne({ 'companyInfo.uniquecompanyid': '123123wfdwedfwfwefwef' }, { new: true, projection: {} })
10:26:34 PM web.1 |  PUT /parserConfig/123123wfdwedfwfwefwef 200 158.118 ms - 2089

UPDATE new information notice

Recently came across this reference: https://github.com/Automattic/mongoose/issues/7011

It mentions:

When calling findOneAndUpdate with an update doc property not in the schema, the debug output shows potential issues. Why does updating work through Studio 3t but not via custom code?

Answer №1

To activate debug logging, use the code mongoose.set('debug', true);. This will display all executed queries. The issue might be linked to a misspelled attribute or an incorrect object id. If this solution doesn't work, kindly provide the debug results in your question so I can modify my response accordingly.

Answer №2

According to the latest version of Mongoose (v7.6.2), the documentation emphasizes that:

The strict option, which is enabled by default, ensures that values not specified in our schema are not saved to the database when passed to our model constructor.

Like you, I also faced challenges defining a schema for my collection due to the varying nature of my documents. The solution that worked for me was including strict: false in the schema of the collection.

import { Schema } from 'mongoose';

const DynamicDocumentSchema = new Schema(
  { bar: String },
  { strict: false }
);

ADDITIONAL NOTE

If anyone is curious, it is possible to include strict: false in the update query as well. This will override any set value of strict in the schema.

await DynamicDocumentModel.findByIdAndUpdate(
  docId,
  {
    $set: <whatever_update>
  },
  { strict: false }
);

Answer №3

I encountered a similar issue with findOneAndUpdate in Mongoose. After researching extensively through various articles and videos, I discovered that Mongoose's schema constructor allows for a second options argument.

One of these options is "strict", which ensures that the values passed to MongoDB via the model instance align with what is specified in the schema.

By setting the option { strict: true }, any discrepancies between the schema and the input values will result in a failed update. To override this behavior, set strict to false.

Interestingly, none of the resources I consulted mentioned these options. It wasn't until I delved into the documentation at https://mongoosejs.com/docs/2.7.x/docs/schema-options.html that everything finally clicked for me.

Answer №4

Not too long ago, I encountered a similar problem. The solution that worked for me was to remember that findOneAndUpdate(query, rule) operates asynchronously. Therefore, you need to use either await or then to handle it properly.

For example: var savedObj = await MyObj.findOneAndUpdate(query, newobj)

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

Implementing Styled API in TypeScript with props: A Comprehensive Guide

I'm currently working on styling a component using the new styled API, not to be confused with StyleComponents. const FixedWidthCell = styled(TableCell)((props: { width: number }) => ({ width: props.width || 20, textAlign: "center", })) The i ...

An error was encountered when attempting to convert a value that is either undefined or null to an object in Angular 9

Upon invoking a service call that interacts with an API to retrieve JSON data, I encountered an issue during the build pipeline of my application. The error message "Uncaught (in promise) TypeError: Cannot convert undefined or null to object." ha ...

Using Javascript or Typescript, update the view to display the user's name instead of their user ID

I own a collection of car models. Each individual car is associated with a unique userid. Furthermore, each user model contains both a userid and a corresponding username. In my view, I aim to showcase all of my car models alongside their respective usern ...

My NodeJS application refuses to host my static files

Despite encountering numerous instances of my issue, none of the solutions seemed to work. I am unable to locate my server root as neither of the provided paths seem to be correct. Static files cannot be found under la-wars > public > css > file, ...

Error in Angular TypeScript occurs when attempting to read properties of an undefined value

Here is the interface that I am working with: export interface IQuest { Id: number, lat: number, lon: number, Question:string, Answer:boolean, IsDone:boolean, Correct:boolean, Range:number} Along with the following component: export class AppComponent imp ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

If the user clicks outside of the navigation menu, the menu is intended to close automatically, but unfortunately it

I have a nav file and a contextnav file. I've added code to the nav file to close the navigation when clicking outside of it, but it's not working. How can I ensure that the open navigation closes when clicking outside of it? Both files are in ts ...

Full compatibility with Angular 2 is now available on Visual Studio 2015 with the added support of

I have some inquiries regarding Visual Studio 2015, Resharper 10, and Angular 2. Is there any syntax highlighting support for HTML markup in TypeScript files in Visual Studio 2015 or Resharper 10? For example, when using a multiline string in a componen ...

Having trouble with Primeicons not displaying correctly in the tree component

Take a look at my code: https://github.com/d1rtyW0lf/aqp-regroupement Here are the styles I'm using: "styles": [ "node_modules/primeicons/primeicons.css", "node_modules/primeng/resources/primeng.min.css", "node_modules/primeng/resour ...

The customization of primary and secondary palettes in React MUI5 with TypeScript theme is restricted and cannot

Our design team put together numerous custom palettes and additional properties. While this posed no problem in JS, transitioning to TS has proven to be quite challenging. I managed to prevent any errors from being thrown in the createTheme file, but using ...

The binding of data in ng2-select encountered an error

Successfully implementing ng2-select to bind an array of objects to a dropdown. It worked seamlessly with an array of strings. private category: Array<object> = [{ "value": 1, "text": "Table" }, { "value": 2, "text": "Chair" }, { "value": 3, "text": ...

Is it possible to inject a descendant component's ancestor of the same type using

When working with Angular's dependency injection, it is possible to inject any ancestor component. For example: @Component({ ... }) export class MyComponent { constructor(_parent: AppComponent) {} } However, in my particular scenario, I am tryin ...

Tips for incorporating pagination into the code sample with the query

Can someone help me with implementing items per page functionality, current and next page navigation, and fetching data in chunks from the backend using Sequelize? // controller const getdailyExpense = async (req, res) => { try { const response = ...

Incompatibility Issues with TypeScript Function Overloading

In the process of setting up an NgRx store, I came across a pattern that I found myself using frequently: concatMap(action => of(action).pipe( withLatestFrom(this.store.pipe(select(fromBooks.getCollectionBookIds))) )), (found at the bottom ...

What is the best way to tally up the letters within a table?

Currently, I am working on a task to count letters and display them in a table. The existing table is functional but has too many rows and incorrect counts. A 2 ...

After the populate() method, I am unable to modify the Mongoose results

I've encountered an issue with my query while using Mongoose and Lodash: Book .find() .pupulate({ path: 'authors.profile', // find all books and populate the authors.profile field select: 'name' }) .exec() .then( ...

Forbidden access to Handlebars properties in Node.js

I encountered an issue: Handlebars: Access has been denied to resolve the property "status" because it is not an "own property" of its parent. You have the option to add a runtime parameter to bypass this check and warning: This is t ...

Typescript is throwing an error stating that utilizing 'undefined' as an index type is invalid

When working with TypeScript and React, I pass xs, sm, md, lg as props to the component. Each size corresponds to a specific pixel value (14px, 16px, 18px, 24px) that is then passed to an Icon component. The errors mentioned in point (1) occur at the line ...

Generating a d.ts file for images in Typescript using automation techniques

Currently, I am working on a React application that utilizes TypeScript and webpack. I am aware that in TypeScript, when importing an image file, it is necessary to create a d.ts file in the current directory and include the following code: // index.d.ts ...

Revising the passport local strategy with promisification. Trouble arises with the implementation of .catch()

Implementing hash password functionality in an express + passport + local strategy app using bcrypt has been successful: var bcrypt = require('bcrypt-nodejs'); familySchema.pre('save', function(next) { var family = this; var SALT_ ...