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

Tips on Dividing a String with a Regular Expression

Does anyone know how to use regex in order to split a string? For example: Here is the string I want to work with. String Temp = "/dev/sda 398G 4.9G 373G 2% /mnt/internal"; I am looking to separate this string into different groups with thei ...

When I incorporate Express into my React project, I encounter an error stating that the prototype

After attempting to set up a basic React project that connects to a MySQL database, I encountered an error. When requiring 'express' and rebuilding the project, I received the following message when trying to open it in the browser: "Uncaught Ty ...

Deleting a user's posts along with the user: A guide

router.delete('/delete',authenticate,async(req, res)=>{ const user = User.findById(req.rootUser._id) { try{ await Post.deleteMany({postedBy:rootUser}) await User.findByIdAndDelete(req.rootUser._id) res.status(200).j ...

Guide to importing an npm module with a Typescript main file in a Typescript project

I'm struggling to figure out the correct method for importing a Typescript npm module. Here is my current approach: module package.json { "name": "my-module", "main": "src/myModule.ts" } module src/myModule.ts export module MyModule { // Co ...

Sending VSCode to external functions

My primary entrypoint containing the activate() function is: extension.ts import * as vscode from "vscode"; import { subscribe } from "./eventListeners.ts"; export function activate(context: vscode.ExtensionContext) { vscode.command ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

What are the potential risks of using the domain module from npm for handling exceptions in Node.js?

Is it advisable to utilize the domain npm module in nodeJS to capture exceptions that occur in callback functions? ...

When attempting to compile my Angular project using the command ng build --prod, I encountered a server error stating that the document

Everything was running smoothly when I was working on my local machine, but once I uploaded the files generated from ng build --prod to the server, a problem arose. Now, whenever I try to route via a button in my components, an error appears. When I clic ...

Dynamic Angular select options with ngFor causing cascading changes in subsequent selects

In my Angular 5 project, I am attempting to create a set of three <select> elements using *ngFor. I came across a helpful thread on Stack Overflow that provided some guidance (check it out here). However, I've encountered an issue where the sele ...

Exploring methods for interacting with and controlling structural directives in e2e testing

Background: My goal is to permutation all potential configurations of an Angular2 screen for a specified route and capture screenshots using Protractor from the following link: http://www.protractortest.org/#/debugging. Problem: I am struggling to figure ...

Obtain an Instance of a Class Using a Decorator

Delving deep into the world of decorators, I stumbled upon some fascinating ideas for incorporating them into my reflux implementation. My concept involves tagging a store's class method with an action, so that whenever that action is triggered, it au ...

Configuring headers for all responses in Express.js

While working with Express for web services, I require the responses to be encoded in utf-8. I am aware that I can manually set the charset for each response using the following code: response.setHeader('charset', 'utf-8'); However, ...

Is it advisable to implement the Debug NPM Module for use in a production environment?

Do you see any drawbacks to utilizing the debug npm module in a production environment? I believe having access to these logs could be beneficial in troubleshooting any issues that may arise during the payment process. Check out some example debug stateme ...

Guide to creating unit tests for document.URL in Angular 5 specifications

Currently attempting to simulate document.URL = 'dashboard'; however, encountering an issue where it states that I can't assign to url because its readonly property. This problem arose while writing jasmine test cases click here for image de ...

Methods for transforming a TypeScript class instance containing getter/setter properties into a JSON format for storage within a MySQL database

I am currently working on a TypeScript class that includes a getter and setter method: export class KitSection { uid: string; order: number; set layout(layout: KitLayout) { this._layout = new KitLayout(layout); } get layout( ...

Node.js: Utilizing dropdown list selections to query database values

Recently, I delved into the world of nodejs and embarked on a project to create a website featuring two drop-down lists. The challenge I am facing involves passing the selected values from these lists as arguments to a MySQL procedure, with the goal of dis ...

Typescript declaration for a .js file in a diverse project

Hey there! I'm currently in the process of converting my JavaScript React Redux project to TypeScript, and I've decided to kick things off by tackling my redux reducers file. Here's a snapshot of how my project is structured: Project/ .. ...

An interactive script utilizing NodeJS with Express and Python

My interactive python script is designed to communicate with my 3D printer. When I run the script, I input two commands that generate information on stdout: Establish a connection with the printer (USB) at 250000 bauds Retrieve the temperature of the pri ...

Exploring ways to retrieve item metadata from a Stripe checkout session

When setting up a Checkout session, I dynamically create prices using the price_data and product_data properties. I include metadata for each item within the product_data.metadata property. However, after a successful payment is made, I retrieve the sessi ...

Get instant access to the Angular page at your fingertips. Experience the best of both worlds with a hybrid application

Is it possible to create an Angular application that loads only a few pages initially? For example, suppose I have a web application that produces a 25 MB build. Can I separate it and move certain components so they are only loaded when the corresponding U ...