由于某些原因,我无法使用猫鼬和打字稿通过ID更新文档。我正在测试api并将id作为参数传递
我尝试了几种不同的ID更新方法。我可以通过比较其他任何字段来进行更新,但是我需要通过ID进行更新
//This is the controller
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
});
}
}
}
// This is the model
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);
我希望文档记录可以更新到我定义的字段。
答案 0 :(得分:0)
最后,我想使用表单数据(基于模型)并更新文档并获取最新文档,我这样做了:
const updateDFRs = await DfrModel.findByIdAndUpdate({_id: req.params.id}, req.body, {new: true});