M
M
Meyz2018-09-24 12:18:36
JavaScript
Meyz, 2018-09-24 12:18:36

Why doesn't find work in mongoose?

Before that I didn’t work with mongoose, I created a model, added a method, how can I find something in the collection in this method? Now the error is this.find is not a
function

interface IUser extends mongoose.Document{
  isValidUser: () => Promise<boolean>;
}

const userSchema = new Schema({
  id: String,
  login: String,
  password: String,
  regDate: {
    type: Date,
    default: Date.now()
  }
});

userSchema.methods.isValidUser = async (): Promise<boolean> => {
  const {login, password} = this;
  const foundUser = await this.find({login, password});
  return !!foundUser;
};

export const User = mongoose.model<IUser>('user', userSchema);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2018-09-24
@Meyz

The problem is in the arrow function - you need to use full-fledged functions
https://mongoosejs.com/docs/guide.html#methods
Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question