properly type updates
This commit is contained in:
1 parent
d3605b0149
commit
81f623b632
1 file changed
+9
-13
@@ -1,4 +1,4 @@
|
||||
import mongoose from "mongoose";
|
||||
import mongoose, { type UpdateQuery } from "mongoose";
|
||||
import { ISettingsRepository } from "@/repositories/settings/ISettingsRepository.js";
|
||||
import type { Settings, SettingsUpdate } from "@/types/index.js";
|
||||
import { AppSettingsModel, type AppSettingsDocument } from "@/db/models/index.js";
|
||||
@@ -60,26 +60,22 @@ class MongoSettingsRepository implements ISettingsRepository {
|
||||
};
|
||||
|
||||
update = async (settings: SettingsUpdate) => {
|
||||
const update: Record<string, any> = { $set: {}, $unset: {} };
|
||||
const $set: Record<string, unknown> = {};
|
||||
const $unset: Record<string, string> = {};
|
||||
|
||||
// Iterate through settings and separate into $set and $unset
|
||||
Object.entries(settings).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
// Unset undefined or empty string values
|
||||
update.$unset[key] = "";
|
||||
$unset[key] = "";
|
||||
} else {
|
||||
// Set defined values
|
||||
update.$set[key] = value;
|
||||
$set[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
// Clean up empty operators
|
||||
if (Object.keys(update.$set).length === 0) {
|
||||
delete update.$set;
|
||||
}
|
||||
if (Object.keys(update.$unset).length === 0) {
|
||||
delete update.$unset;
|
||||
}
|
||||
const update: UpdateQuery<AppSettingsDocument> = {
|
||||
...(Object.keys($set).length > 0 && { $set }),
|
||||
...(Object.keys($unset).length > 0 && { $unset }),
|
||||
};
|
||||
|
||||
await AppSettingsModel.findOneAndUpdate({}, update, {
|
||||
upsert: true,
|
||||
|
||||
Reference in new issue
Block a user