2
votes

I'm having trouble populating my user model with typescript. I have a property of the user's scheme which is the reference to his profile. To implement mongoose with typescript I had to define a tpo / interface in addition to the schema. My problem is that I do not know what type I have to assign to the profile property. Because if I run the query without populating it, it will be an "ObjectId", but if I populate it will contain the whole profile document.

export type UserModel = mongoose.Document & {
  name: string;
  username: string; 
  email: string;
  password: string; 
  profile: Schema.Types.ObjectId; // If I leave this property with this type, in case I populate a typescript query it would give me an error. 
};


export const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true,
    unique: true
  },
  email: {
    type: String,
    unique: true,
    required: true
  },

  password: {
    type: String,
    required: true
  },
  profile: {
    type: Schema.Types.ObjectId,
    ref: "Profile"
  }
});

export default model<UserModel>("User", UserSchema);
2
What actually is the question? How to see the "populated" properties in code assistance in later code? Note that "typescript" is not "run-time checking". So this really is not about the "model" definition but more about the code which is attempting to access the structure. See How to define model in combination with using mongoose populate? if that is what you are really getting at. - Neil Lunn
@Neil Lunn Thank you very much, it was just what I was looking for. Now I think I need to eliminate the question so as not to leave a useless duplicate - Niccolò Caselli

2 Answers

2
votes

My problem is that I do not know what type I have to assign to the profile property.

You are going to need to define 2 types/interfaces.

export default model<UserModel>("User", UserSchema);

This export will have to use a different interface in which you have the populated "Profile" document.

For the schema itself you can leave it as an objectID type.

0
votes

Try to set the populate pointing to the model, this should do the trick

 User.find({}).populate([{"path":"profile", "model":"Profile" }])