title: Mongoose custom validator: check if value exists in database
body: <p>I am currently trying to add a custom validator to my schema. For some reason I cannot query the database. Does anyone know a solution for my problem? </p>
  
  <p>This is the schema:</p>
  
  <pre><code>var Portfolio = new Schema({
      title: {
          type: String,
          required: [true, 'Title is required']
      },
      thumbnail: {
          type: String,
          required: [true, 'Thumbnail is required'],
      },
      description: String,
      date: Date,
      images: [String],
      categories: [Schema.Types.ObjectId],
      order: Number,
      slug: {
          type: String,
          validate: {
              validator: slugExists,
              message: 'Slug already exists, choose a different title',
          }
      }
  }, options);
  </code></pre>
  
  <p>This is the method that checks whether the data exists:</p>
  
  <pre><code>function slugExists(value) {
      this.model.count({slug: value}, function(err, count) {
          if (error) {
              return err;
          }
          return count &gt; 0;
      });
  }
  </code></pre>
  
  <p>When I run the application I get the following error message:</p>
  
  <pre><code>TypeError: this.model.count is not a function
  </code></pre>
  
  <p>I have also tried to use the following:</p>
  
  <pre><code>mongoose.model['portfolio'].count(...)
  </code></pre>
  
  <p>but the result is the same.</p>
  
  <p>I have been trying to fix the problem for two hours now, even tried different approaches (for example the pre hook). But adding the custom validation directly to the Schema feels like the cleanest entry.</p>
  
  <p>Hope you have a solution for me. Many thanks in advance!</p>
  
  <p>Jeffrey</p>