簡體   English   中英

使用 mongoose 將驗證器添加到現有模式

[英]Adding a validator to an existing schema with mongoose

我有一個看起來像這樣的 mongoose 架構:

const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        minlength: 4,
        maxlength: 20,
        validate: {
            validator: username => !username.startsWith('banned_prefix')
            msg: 'This username is invalid',
            type: 'username-validation-1'
        }
    }
});

我希望架構看起來像這樣:

const userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        minlength: 4,
        maxlength: 20,
        validate: [
            {
                validator: username => !username.startsWith('banned_prefix')
                msg: 'This username is invalid',
                type: 'username-validation-1'
            },
            {
                validator: username => !username.startsWith('new_banned_prefix')
                msg: 'This username is invalid',
                type: 'username-validation-2'
            }
        ]
    }
});

鑒於數據庫和架構已經存在並且我不想完全刪除和重置數據庫,我該怎么做?

我嘗試使用基於https://docs.mongodb.com/manual/core/schema-validation/#exist的本機 mongodb 節點驅動程序編寫遷移。 但是,似乎 mongoose 實際上並未為架構中指定的驗證器添加本機 mongodb 驗證器。 也就是說,當我打印出集合的驗證器數據時,我得到一個空的 object:

// prints {}
console.log((await db.listCollections({ name: 'users' }).toArray())[0].options.validator);

我不想添加這個新的驗證器,使其不同於我在架構上擁有的現有驗證器。

實際上,這看起來根本不是問題,因為我認為 mongoose 沒有使用 mongodb 本機驗證器,因此不需要對實際數據庫進行任何更改。 ZCCADCDEDB567ABAE643E15DCF0974E503Z 將自動獲取這樣的驗證器更改,無需遷移。

This wasn't clear to me at first because I was trying to manually recreate the model with the mongoose.model function and was getting errors about overwriting an existing model.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM