How can I use MongooseArray.prototype.pull() with typescript?
Solution 1:
I faced a similar problem to properly type the subdocuments. I propose you the following solution in order to keep both the DTO interface and the model interface separated and strongly typed. The same would apply for your PostDoc
.
UserDoc DTO
interface UserDoc {
email: string;
password: string;
posts: PostDoc[];
name: string;
status: string;
}
UserDoc Model
export type UserDocModel = UserDoc & mongoose.Document & PostDocModel & Omit<UserDoc , 'posts'>
interface PostDocModel {
posts: mongoose.Types.Array<PostModel>;
};
We replace the posts: PostDoc[]
property with Omit for our mongoose array of PostModel
, maintaining the properties synchronized. Inspiration from https://stackoverflow.com/a/36661990
In this way we could access every mongoose array method such as pull
, pop
, shift
, etc. (https://mongoosejs.com/docs/api.html#Array)
const user = await this.userdocModel.findById(userId).exec();
user.posts.pull(postId);
Exporting the model
const User = mongoose.model<UserDocModel>('User', userSchema);
export default User;