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.