我想要按ID更新数据,但在更新之前,我想删除先前存储在该ID上的数据。会有什么过程?
Controller.ts
public updateVendorServiceSpecialPrice = async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => {
try {
if (req.body.vendorServiceId!='') {
let results = await this.ServicesService.updateVendorServicesSpecialPrice(req.params.vendorServiceId, req.body);
if (results != false) {
this.success(res, 'Updated Successfully', 200, results._id);
}
}
return await this.error(res, 'Something Went Wrong!.', 500);
} catch (e) {
next(e)
}
}
Service.ts
public async updateVendorServicesSpecialPrice(
vendorServiceId: any,
data: any
): Promise<any | Error> {
try {
return new Promise((resolve, reject) => {
vendorServiceSpecialPriceSchema.findByIdAndUpdate(
vendorServiceId,
{ ...data },
(err: any, success: any) => {
if (err) {
reject(err);
}
if (!success) {
resolve(false);
} else {
resolve(success);
}
}
);
});
} catch (e) {
console.log('service error\n', e);
throw e;
}
}
我试图用这种方式解决这个问题,也许我错了,什么会带来正确的过程:
public async updateVendorServicesSpecialPrice(
vendorServiceId: any,
data: any
): Promise<any | Error> {
try {
return new Promise((resolve, reject) => {
vendorServiceSpecialPriceSchema.deleteOne({vendorServiceId})
vendorServiceSpecialPriceSchema.findOneAndUpdate(
vendorServiceId,
{ ...data },
{ returnNewDocument: true },
(err: any, success: any) => {
if (err) {
reject(err);
}
if (!success) {
resolve(false);
} else {
resolve(success);
}
}
);
});
} catch (e) {
console.log('service error\n', e);
throw e;
}
}
感谢您抽出时间..。
1条答案
按热度按时间y0u0uwnf1#
您可以使用Mongoose中的findOneAndReplace方法:
如果刚刚添加的数据对象中没有_id: