Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function parameter type for Mongoose schema, in Typescript?

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.

like image 847
Andre M Avatar asked Sep 03 '25 17:09

Andre M


1 Answers

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.

like image 74
Acuervov Avatar answered Sep 07 '25 02:09

Acuervov