Reputation: 715
I am using Node with Typescript. I am finding a mongodb document and updating some values into it and then saving it. On the statement save it is showing this error. Below is the code:
let user = await User.findById(id);
if (user) {
user = Object.assign(user, req.body);
await user.save(); // on this line error is shown
} else {
throw "User not found";
}
On the line await user.save() it is showing this error.
Upvotes: 1
Views: 2092
Reputation: 2539
I'm not sure why, but mutating the user
variable seems to be causing the issue.
Rewriting it with a new variable works fine in the typescript playground for me (I had to cheat a bit to avoid having a real Mongoose model and I made up the types, but it should be the same idea):
type User = {
email: string;
save: () => Promise<void>
}
declare let user: User | null;
if (user) {
const newUser = Object.assign(user, { email: "[email protected]"})
newUser.save(); // on this line error is shown
} else {
throw "User not found";
}
Upvotes: 1
Reputation: 33041
This means that user can be null
.
You can use conditional statement:
if(user){
await user.save()
}
await user?.save()
Upvotes: 1