0

I am reading a code that makes me confused! This is the code:

import mongoose from 'mongoose';
import { Password } from '../services/password';

// An interface that describes the properties
// that are requried to create a new User
interface UserAttrs {
  email: string;
  password: string;
}


// An interface that describes the properties
// that a User Document has
interface UserDoc extends mongoose.Document {
  email: string;
  password: string;
}

// An interface that describes the properties
// that a User Model has
interface UserModel extends mongoose.Model<UserDoc> {
  build(attrs: UserAttrs): UserDoc;
}

const userSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true
    }
  },
  {
    toJSON: {
      transform(doc, ret) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.password;
        delete ret.__v;
      }
    }
  }
);

userSchema.pre('save', async function (done) {
  if (this.isModified('password')) {
    const hashed = await Password.toHash(this.get('password'));
    this.set('password', hashed);
  }
  done();
});

userSchema.statics.build = (attrs: UserAttrs) => {
  return new User(attrs);
};

const User = mongoose.model<UserDoc, UserModel>('User', userSchema);

export { User };

I can't understand why it makes the UserModel first time here:

    interface UserModel extends mongoose.Model<UserDoc> {
      build(attrs: UserAttrs): UserDoc;
    }

Then for the second time here:

const User = mongoose.model<UserDoc, UserModel>('User', userSchema);

I also don't know why at this part of the code:

userSchema.statics.build = (attrs: UserAttrs) => {
  return new User(attrs);
};

It says it returns a UserModel but at the interface declaration here:

interface UserModel extends mongoose.Model<UserDoc> {
  build(attrs: UserAttrs): UserDoc;
}

It says it should return a UserDoc?

GoodMan
  • 542
  • 6
  • 19

0 Answers0