【问题标题】:mongoose: vaildate portion of schema searching for field already in db猫鼬:验证模式的部分搜索已经在数据库中的字段
【发布时间】:2017-02-27 03:39:38
【问题描述】:

我正在尝试为 mongoose 对象编写自定义验证器。这个想法是name 字段必须是不同集合中预先存在的对象的名称值。我这样做是这样的:

var seshSchema = new Schema(
    {
        student:
            {
                type: String,
                validate: [
                function(input)
                {

                    studentColl.find({name: input},function(err, result){
                        if(err)
                        {
                            throw err;
                        }

                        return result.length > 0; //how do I make this get returned by the function in vaildate's array?

                    });


                }, "nope"]
            },
        tutor: {type: String},
        blockTimes: [blockTime],
        record : [pastSession]
    }
);

我要做的是根据不同集合 (studentColl) 中是否存在某些标准来验证这篇文章。这可能吗?

【问题讨论】:

    标签: node.js mongodb asynchronous mongoose schema


    【解决方案1】:

    也许这就是你要找的东西:Mongoose Validation

    他们在那里描述了异步验证器 here 的用法。

    根据本文档,您的代码应如下所示:

    var seshSchema = new Schema({
        student: {
            type: String,
            validate: {
                validator: function(v, cb) {
                    setTimeout(function() {
                        studentColl.find({ name: v }, function(err, result) {
                            if (err) {
                                cb(false);
                            } else {
                                cb(result.length > 0);
                            }
                        });
                    }, 1);
                }
            }
        },
        ...
    });
    

    【讨论】:

    • @Schulace:这个答案对你有帮助吗?
    • 我试过这样做,但是那里的返回只返回传递给 find 的函数,而不是第一个函数。基本上我需要同步运行这个异步方法。
    • 我更新了我现在使用异步验证器的答案。也许这就是你要找的?
    • 我找到了使用 deasync 模块的不同解决方案,但我一定会查看您发布的解决方案。非常感谢您的帮助
    • 更新:您的解决方案不那么笨拙,尽管超时是不必要的,并且很可能只是在文档中用作异步示例。
    猜你喜欢
    • 1970-01-01
    • 2021-02-23
    • 2017-01-14
    • 2020-02-17
    • 2019-06-16
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 2021-06-20
    相关资源
    最近更新 更多