I am trying to work out what is the right parameter type, for a mongoose document passed as parameter to a function.
Starting with the definition:
import mongoose, { Schema, Document } from 'mongoose';
export interface IUser extends Document {
email: string;
firstName: string;
lastName: string;
}
const UserSchema: Schema = new Schema({
email: { type: String, required: true, unique: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true }
});
export default mongoose.model<IUser>('User', UserSchema);
Then we have a function that looks like:
function updateUser(user: IUser) {
user.firstName = 'something';
user.lastName = 'somethingElse';
user.save();
}
The issue here is that the Document type doe not have a save()
function, so it fails. At the same time I can't specify User
, since it throws the error "'User' refers to a value, but is being used as a type here.ts(2749)".
The user parameter is an object of a findOne()
operation.
This works for me:
import { Model } from "mongoose";
function updateUser(user: Model<IUser>) {
cost newUser = new user({
firstName:'something',
lastName:'somethingElse',
})
return newUser.save();
}
if you are working in a different file you will need to import also the IUser interface.
Let me know if it works for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With