Niccolò Caselli
Niccolò Caselli

Reputation: 882

Populate a query with mongoose in typescript

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);

Upvotes: 2

Views: 4199

Answers (2)

Vincent Newkirk
Vincent Newkirk

Reputation: 194

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.

Upvotes: 2

Rodrigo Baute
Rodrigo Baute

Reputation: 114

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

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

Upvotes: 0

Related Questions