DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

umasankar-swain
umasankar-swain

Posted on

How to update a record and delete that same record before update (nest js & mongoDB)

I want to update a record by its id but before update, i want to delete the previously stored data on that same record.What would be the process?

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

I am trying in this way to solve this,may be I am wrong,what would br the right process:

    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;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for your time....

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.