如何在更新之前更新特定数据并删除先前存储的数据(MongoDB With Nest Js)

lx0bsm1f  于 2022-10-22  发布在  Go
关注(0)|答案(1)|浏览(180)

我想要按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;
    }
}

感谢您抽出时间..。

y0u0uwnf

y0u0uwnf1#

您可以使用Mongoose中的findOneAndReplace方法:

vendorServiceSpecialPriceSchema.findOneAndReplace(
  { _id: new Types.ObjectId(vendorServiceId) }, // You need to import Types from mongoose module
  data,
  (err: any, success: any) => {
    if (err) {
      reject(err);
    }
    if (!success) {
      resolve(false);
    } else {
      resolve(success);
    }
  }
);

如果刚刚添加的数据对象中没有_id:

{_id: vendorServiceId, ...data}

相关问题