Mongoose自定义验证器:检查数据库中是否存在值

Mongoose自定义验证器:检查数据库中是否存在值,mongoose,mongoose-schema,Mongoose,Mongoose Schema,我目前正在尝试将自定义验证器添加到我的架构中。由于某种原因,我无法查询数据库。有人知道我的问题的解决办法吗 这是模式: var Portfolio = new Schema({ title: { type: String, required: [true, 'Title is required'] }, thumbnail: { type: String, required: [true, 'Thumbnai

我目前正在尝试将自定义验证器添加到我的架构中。由于某种原因,我无法查询数据库。有人知道我的问题的解决办法吗

这是模式:

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);
这是检查数据是否存在的方法:

function slugExists(value) {
    this.model.count({slug: value}, function(err, count) {
        if (error) {
            return err;
        }
        return count > 0;
    });
}
运行应用程序时,我收到以下错误消息:

TypeError: this.model.count is not a function
我还尝试使用以下方法:

mongoose.model['portfolio'].count(...)
但结果是一样的

我已经尝试了两个小时来解决这个问题,甚至尝试了不同的方法(例如pre-hook)。但是直接向模式添加自定义验证感觉是最干净的条目

希望你能给我一个解决办法。非常感谢


Jeffrey可以使用
预保存方法
考虑下面的示例,其中尝试在用户模型中验证用户名:

   UserSchema.pre('save', function (next) {
   var self = this;
   mongoose.models["User"].findOne({username: self.username}, function (err, user) {
      if (!user) {
          next();
      } else {
          next(new Error("Username already exists!"));
      }
  });

当我测试不同的解决方案时,我发现一篇帖子回答了我的问题()

这就是我一直在寻找的解决方案:

function slugExists(value, callback) {
    this.constructor.count({slug: value}, function(err, count) {
        if (err) {
            next(err);
        }
        callback(count === 0);
    });
}

Portfolio.pre('validate', function(next) {
    this.slug = slugify(this.title);
    next();
});

旁注:slug将根据标题生成。这就是为什么我必须使用“验证”预钩子,以便在验证之前就已经设置了slug(否则将忽略验证程序,因为它没有任何值,也不是必需的)

Hm。。。为什么不在
slug
上添加一个
unique
索引呢?尽管如此,这可能会指引你到某个地方。你试过猫鼬。模型(‘公文包’)。计数(…)
?谢谢你的回答,迈克。遗憾的是,这两种解决方案都不起作用。我一直收到以下错误:无法读取未定义的属性“count”。感谢您提出解决方案。不过我不想使用pre-hook,因为接下来我必须考虑另一种处理错误消息的方法(正如您在我的示例中看到的,我使用Mongoose的自定义消息来处理错误)。通过使用上述方法,您也可以得到相同的自定义错误。您也可以在自定义函数中使用钩子函数。感谢您的回复。最终我找到了我一直在寻找的解决方案。我仍然很好奇如何在pre-hook中构建相同的自定义错误。我会调查的!