Skip to content

Commit bbf042a

Browse files
committed
refactor: improve survey update logic by using $set operator for partial updates
1 parent db088c3 commit bbf042a

File tree

4 files changed

+13
-12
lines changed

4 files changed

+13
-12
lines changed

backend/src/controllers/survey.controller.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -123,14 +123,16 @@ class SurveyController {
123123
try {
124124
const Survey = mongoose.model('Survey');
125125
const { id } = req.params;
126-
const updated = await Survey.findOneAndUpdate({
127-
id: { $eq: Number(id) }
128-
}, {
129-
// we don't want to update all fields... just the ones passed in the body.
130-
...req.body,
131-
hits: 0,
132-
status: 'completed'
133-
});
126+
const updated = await Survey.findOneAndUpdate(
127+
{ id: { $eq: Number(id) } },
128+
{
129+
$set: {
130+
...req.body,
131+
hits: 0,
132+
status: 'completed'
133+
}
134+
}
135+
);
134136
if (updated) {
135137
res.status(200).json({ _id: id, ...req.body });
136138
} else {

backend/src/routes/index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import mongoSanitize from 'express-mongo-sanitize';
1111

1212
const router = Router();
1313

14-
1514
router.use(mongoSanitize());
1615

1716
router.get('/', (req: Request, res: Response) => {

backend/src/services/survey.service.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ class SurveyService {
1616
throw new Error('Invalid survey data provided');
1717
}
1818
const Survey = mongoose.model('Survey');
19-
const result = await Survey.updateOne({ id: survey.id }, survey);
20-
19+
const result = await Survey.updateOne({ id: survey.id }, { $set: survey });
20+
2121
// Check if the update modified any document.
2222
if (result.modifiedCount === 0) {
2323
throw new Error('Survey update failed: no document was modified');

backend/src/services/target.service.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ class TargetValuesService {
4747
async updateTargetValues(data: Targets) {
4848
try {
4949
const Targets = mongoose.model('Targets');
50-
const targets = await Targets.findOneAndUpdate({}, data, { new: true, upsert: true });
50+
const targets = await Targets.findOneAndUpdate({}, { $set: data }, { new: true, upsert: true });
5151
return targets;
5252
} catch (error) {
5353
throw new Error(`Error updating target values: ${error}`);

0 commit comments

Comments
 (0)