Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter.

I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by comparing other fields, but specifically need to update by the ID.

//Controller code snippet

import DfrModel from './dfr.model';
import { Request, Response } from 'express';
import config from '../../config/config';
import bodyParser = require('body-parser');
import DFRActivityModel from './DFRActivity.model';
import * as mongoose from "mongoose";

export default class DfrController {

public updateOne = async (req:Request, res:Response): Promise<any> => {
    const dfr = new DfrModel(req.body);
    console.log(req.params.id);
    try {
        const updateDFRs = await DfrModel.findByIdAndUpdate( mongoose.Types.ObjectId(req.params.id),{$set:{'projectName': 'CHANGED 1234', 'projectNumber': '12345'}}); 
        //const updateDFRs = await DfrModel.findByIdAndUpdate(req.params.id,{$set:{'projectName': 'CHANGED 1234', 'projectNumber': '12345'}}); //Does not work either

        if (updateDFRs === null || updateDFRs.nModified === 0) {
            return res.status(404).send({
                success: false,
                message: 'Error Saving DFR',
                data: null
              });
        }

        res.status(200).send({
            success: true,
            data: dfr
          });

    } catch (err) {
        res.status(500).send({
            success: false,
            message: err.toString(),
            data: null
        });
    }
}

}

// Model code snippet
import * as mongoose from "mongoose";
const Schema = mongoose.Schema;

const DFRSchema = Schema ({
    _id: {
        type: String,
    },
    projectName: {
        type: String,
        required: true,
        trim: true
    },
    projectNumber: {
        type: String,
        required:false,
        trim: true
    }
};
export default mongoose.model("DFR", DFRSchema);

Expecting the document record to update according to the defined fields.

Answer №1

Ultimately, my goal was to utilize the form data (derived from the model) to make updates to the document and retrieve the most recent version of the document. Here's how I achieved it:

const updatedDocument = await DocumentModel.findByIdAndUpdate({_id: req.params.id},  req.body, {new: true});

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

"Create a separate function for the pipeable operator in RXJS for enhanced code

After working on some code, I came up with the following implementation this.form.valueChanges.pipe( take(1), map(val => // doSomething), exhaustMap(val => // someInner observable logic return of({someValue}) ) ).subscrib ...

What is the correct way to use Observables in Angular to send an array from a Parent component to a Child

Initially, the task was to send JSON data from the parent component to the child component. However, loading the data through an HTTP request in the ngOnInit event posed a challenge as the data wasn't being transmitted to the child component. Here is ...

Navigating json data in angular 6

I retrieved a JSON object in the following format response = [ { 'a': [ { 'b': [ { 'c': [ { 'name': 'abc', 'value': 900 ...

Tips for prohibiting the use of "any" in TypeScript declarations and interfaces

I've set the "noImplicitAny": true, flag in tsconfig.json and "@typescript-eslint/no-explicit-any": 2, for eslint, but they aren't catching instances like type BadInterface { property: any } Is there a way to configure tsco ...

Having trouble locating the type definition file for 'cucumber' when using the Protractor framework with Cucumber and Typescript

Currently immersed in working on Protractor with Cucumber and TypeScript, encountering a persistent issue. How can the following error be resolved: Cannot locate the type definition file for 'cucumber'. The file exists within the pr ...

What is the method for creating an object type that necessitates a key determined by a variable?

Is it feasible to create a custom type in TypeScript that can check if a given key exists within the Type definition? I am specifically using noUncheckedIndexAccess: true configuration. interface one { foo: string; bar: string; } interface two { b ...

Creating hierarchical TreeNode structure in TypeScript

As I work with a flat one-dimensional array of type TreeNode (view interface definition below), my goal is to recursively traverse the array and add subsequent array elements as children. While attempting a non-recursive approach using a buffer, I encount ...

Perform TypeScript type checks exclusively on a Next.js project

In my current project using Next.js with TypeScript in a mono-repo setup, I have multiple applications under the same repository. When pushing changes to this setup, various hooks are triggered locally to ensure that the modifications meet the required sta ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

An issue has occurred: Unable to locate a supporting object 'No result' of type 'string'. NgFor is only compatible with binding to Iterables like Arrays

I am attempting to utilize this code to post data from a web service. service.ts public events(id: string): Observable<Events> { ...... return this.http.post(Api.getUrl(Api.URLS.events), body, { headers: headers }) .map((re ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Tips for monitoring changes to files while developing a NestJs application within a Docker container

Having an issue with NestJS and Docker here. Trying to run the development script using npm start: dev, but encountering a problem where the app runs fine but doesn't detect any changes in the source files, hindering the development process. Here&apo ...

"Although the Set-cookie is present in the response header, it is not being properly

I developed a GraphQL server using apollo-server-express, and it is currently running on localhost:4000. Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header However, when checking the storage > ...

Tips for utilizing ngIf based on the value of a variable

Here is the code from my file.html: <button ion-button item-right> <ion-icon name="md-add-circle" (click)="save();"></ion-icon> </button> The content of file.ts is: editmode = false; I am trying to achieve the foll ...

Set an array to a JSON object as a fresh entity

My challenge involves working with an array that contains certain values. let myArray = [value1, value2]; I am looking to generate a JSON object in the format shown below: { "field": "[value1, value2]" } ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

The function 'makeDecorator' does not support function calls when being accessed

Resolved by @alexzuza. Check out his solution below - major props! The issue was with the node_modules folder in the ng2-opd-popup directory, it needed to be removed and the src/tsconfig.app.json file had to be adjusted accordingly. Make sure to also refer ...

I am encountering an issue where Typescript paths specified in the tsConfig.app.json file are not resolving properly

I have defined path settings in my tsconfig.app.json file like this: "paths": { "@app/core": ["./src/app/core"] } Every time I run a test that includes import statements with relative paths, it throws the following error: ...