我想要按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;
}
}
架构:
const SpecialPriceSchema = new Schema({
_id: { type: Schema.Types.ObjectId },
vendorServiceId: { type: String, ref: 'vendorService', index: true },
vendorId: { type: String },
startDate: { type: String },
endDate: { type: String },
recurrenceType: { type: Number }, //1-All Day,2 weekend,3 custom
priceType: { type: Number }, //1- total,2 per piece/per person,3 per hour
minGuestRange: { type: Number, default: 0 },
maxGuestRange: { type: Number, default: 0 },
price: { type: Number, default: 0 },
minCapacity: { type: Number, default: 0 },
maxCapacity: { type: Number, default: 0 },
isBlocked: { type: Boolean, default: false },
isDeleted: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now() },
updatedAt: { type: Date, default: Date.now() }
})
let vendorServiceSpecialPriceSchema = model<IVendorSpecialPrice>('vendorServiceSpecialPrice', SpecialPriceSchema);
export { vendorServiceSpecialPriceSchema }
架构和集合
感谢您抽出时间..。
1条答案
按热度按时间iaqfqrcu1#
您现在看到的可能是ReplaceOne,它替换了基于_id的整个文档
您可以使用Collection tion.replaceOne()方法替换单个文档。ReplaceOne()接受查询文档和替换文档。如果查询与集合中的某个文档匹配,它将用提供的替换文档替换与查询匹配的第一个文档。此操作将删除原始文档中的所有字段和值,并将其替换为替换文档中的字段和值。除非您在替换文档中为_id显式指定了新值,否则_id字段的值保持不变。https://www.mongodb.com/docs/drivers/node/current/usage-examples/replaceOne/
如果有许多要替换的文档,您可以执行循环。例如:
或者,如果您熟悉的话,也可以使用BulkWite。https://www.mongodb.com/docs/manual/reference/method/Bulk.find.replaceOne/