【问题标题】:Execute query in Mongoose schema validation在 Mongoose 模式验证中执行查询
【发布时间】:2016-05-07 16:15:34
【问题描述】:

我试图设置我的 MongoDB 设计,以便有一个 projects 集合和一个 people 集合。 Project 模型架构包含一个 _people 项目,它引用 People 模型。 (相对于 People 模型有一个字段来引用他/她所属的项目。它需要是这样的)

每当在people 容器中创建新文档时,我都需要运行验证,即每个项目只能有一个经理。如果我可以对架构中的元素验证执行查询,这将非常容易,但我不相信这是可能的......

这是当前People 模型的架构:

const peopleSchema = new Schema( {
    name: {
        type: Schema.Types.String,
        required: true,
        minlength: 3,
        maxlength: 25,
        trim: true,
        select: true
    },
    isManager: {
        type: Schema.Types.Boolean,
        default: false,
        validate: {
            validator: function ( v ) {
                // How can I check if there are any existing `people` documents with the 
                // `isManager` set to true, which are referenced by the same project.
                // If I can return a promise from here, then I can just execute a query and verify the results
            },
            message: 'There can be only one manager per each group'
        }
    }
})

正如您在 isManager.validate.validator 函数中看到的那样,我注意到如果此文档 isManager 设置为 true,我需要找到一种方法来检查是否还没有 person 文档被同一个项目也是经理。

知道哪个项目引用了这个文档不是问题,我会在某个地方找到它,我只需要知道如何运行查询.. 这可能吗?

【问题讨论】:

    标签: node.js mongodb validation mongoose mongoose-schema


    【解决方案1】:

    通过使用 Mongooses Middleware 功能,我能够达到预期的效果。在pre-save hook 中设置验证工作得很好

    【讨论】:

    • 你是怎么做到的?我的查询只是挂在钩子的范围内,而在外面工作正常......
    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 2017-10-06
    • 2017-07-21
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多