Struggling to use Mongoose findByIdAndUpdate for updating a document by ID, the operation runs smoothly but changes are not reflected in the database.
In the server log, I only see users.findOne being logged when I trigger the API. Shouldn't Mongoose also execute the update along with it? Creating and deleting users works fine without any issues.
Interface
export interface User {
_id: string;
email: string;
password: string;
}
Model
const userSchema: Schema = new Schema({
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
});
Controller
public updateUser = async (req: Request, res: Response, next: NextFunction) => {
try {
const userId: string = req.params.id;
const userData: CreateUserDto = req.body;
const updateUserData: User = await this.userService.updateUser(userId, userData);
res.status(200).json({ data: updateUserData, message: 'updated' });
} catch (error) {
next(error);
}
};
Service
public async updateUser(userId: string, userData: CreateUserDto): Promise<User> {
if (isEmpty(userData)) throw new HttpException(400, "You're missing userData");
if (userData.email) {
const findUser: User = await this.users.findOne({ email: userData.email });
if (findUser && findUser._id != userId) throw new HttpException(409, `The email ${userData.email} is already in use`);
}
if (userData.password) {
const hashedPassword = await bcrypt.hash(userData.password, 10);
userData = { ...userData, password: hashedPassword };
}
const updatedUser: User = await this.users.findOneAndUpdate({ _id: userId }, { userData }, { new: true });
if (!updatedUser) throw new HttpException(409, "User not found");
return updatedUser;
}
Dtos
import { IsEmail, IsString } from 'class-validator';
export class CreateUserDto {
@IsEmail()
public email: string;
@IsString()
public password: string;
}
Logs when running the update API
mongodbexpress | {"t":{"$date":"2021-08-23T05:19:26.698+00:00"},"s":"I", "c":"STORAGE", "id":22430, "ctx":"Checkpointer","msg":"WiredTiger message","attr":{"message":"[1629695966:698802][1:0x7f5f10065700], WT_SESSION.checkpoint: [WT_VERB_CHECKPOINT_PROGRESS] saving checkpoint snapshot min: 664, snapshot max: 664 snapshot count: 0, oldest timestamp: (0, 0) , meta checkpoint timestamp: (0, 0) base write gen: 2092"}}
server | Mongoose: users.findOne({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="17797260720e7b397478">[email protected]</a>' }, { projection: {} })
server | Mongoose: users.findOne({ _id: ObjectId("6122ae51d922ae0a85b85484") }, { new: true, projection: {} })
server | 2021-08-23 05:19:27 info: PUT /users/6122ae51d922ae0a85b85484 200 75.025 ms -