Skip to content

Commit db1debc

Browse files
authored
Merge pull request #1230 from andypols/fix-mongo-update-user-error
fix: "MongoServerError: The _id cannot be changed" when updating users
2 parents 32bfc70 + 050e70f commit db1debc

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

src/db/mongo/users.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { OptionalId, Document } from 'mongodb';
1+
import { OptionalId, Document, ObjectId } from 'mongodb';
22
import { toClass } from '../helper';
33
import { User } from '../types';
44
import { connect } from './helper';
@@ -55,7 +55,9 @@ export const updateUser = async (user: User): Promise<void> => {
5555
if (user.email) {
5656
user.email = user.email.toLowerCase();
5757
}
58+
const { _id, ...userWithoutId } = user;
59+
const filter = _id ? { _id: new ObjectId(_id) } : { username: user.username };
5860
const options = { upsert: true };
5961
const collection = await connect(collectionName);
60-
await collection.updateOne({ username: user.username }, { $set: user }, options);
62+
await collection.updateOne(filter, { $set: userWithoutId }, options);
6163
};

0 commit comments

Comments
 (0)