Updating a record in a mongoose collection is a tricky thing when your function allows you to update multiple things together. Say you only want to update 3 out of 5 key values of a record. Here is an easy way to do this -
const params = CampaignBatchProspectUtil.sanitiseParams({
prospect: prospectId,
campaignBatch: campaignBatchId,
type,
status: { $ne: CampaignBatchProspectStatus.REMOVED },
});
In the above code, prospectId
, campaignBatchId
and type
all optional. If we pass in null values for any of the above, the record itself will get updated with null values which we don't want. We want only the non-null attributes to get updated.
This is taken care of in the sanitiseParams function as so -
static sanitiseParams<T>(params: T): T {
const sanitisedParams: Partial<T> = {};
Object.keys(params).forEach((key) => {
if (params[key] !== null) {
sanitisedParams[key] = params[key as keyof T];
}
});
return sanitisedParams as T;
}
We have used generics so that the type of params are preserved post sanitising. The sanitise function only returns non-null keys and values.
This can then be passed into something like -
await CampaignBatchProspectRepository
.campaignBatchProspectDB
.findOneAndUpdate(
filterParams,
params,
{ new: true }
);
We can further move the sanitiseParams
function into a common util file that can be used across modules if needed.
Top comments (0)