簡體   English   中英

有沒有辦法使用 mongo 的驗證器驗證插入 mongoDB 的 UUID?

[英]Is there a way to validate a UUID inserted in a mongoDB using mongo's validator?

我正在使用 migrate-mongo 來管理我的數據庫遷移,我正在嘗試創建一個新的遷移來創建一個帶有驗證器的集合並在其中插入值。 我想為 _id 屬性使用 UUID,我正在使用 uuid-mongodb 庫來生成它。 我的問題是我無法在不導致數據插入失敗的情況下在驗證器中設置我的 _id 的 bsonType。 有什么方法可以確保插入集合中的文檔的 id 是 UUID? 我知道 mongoose 可以幫助我解決這個問題,但我希望在數據庫級別進行驗證。 另外,當我沒有在驗證器中指定 _id 的 bsonType 時,插入有效,只有當我指定它時它才會驗證失敗。

這是我的遷移代碼

const MUUID = require("uuid-mongodb");

module.exports = {
  async up(db) {

    //Will use https://docs.mongodb.com/manual/tutorial/model-tree-structures-with-materialized-paths/

    await db.createCollection("itemCategories", {
      validator: {
        $jsonSchema: {
          required: ["name"],
          bsonType: "object",
          properties: {
            _id: {"object"}, //I also tried with binData
            name: {
              bsonType: "string",
              maxLength: 50,
            },
            path: {
              bsonType: ["string", "null"],
              pattern: "^,([^,]+,)+$"
            }
          },
          additionalProperties: false,
        }
      },
    });
    await db.collection("itemCategories").createIndex({"name": 1}, {unique: true});
    await db.collection("itemCategories").insertMany([
      {_id: MUUID.v4(), name: "Sport", path: null},
      {_id: MUUID.v4(), name: "Tool", path: null},
      {_id: MUUID.v4(), name: "Entertainment", path: null}
    ]);
  },

  async down(db) {
    await db.dropCollection("itemCategories");
  }
};

這是我在運行時遇到的錯誤

ERROR: Could not migrate up 20210627041314-create-categories.js: Document failed validation BulkWriteError: Document failed validation
    at OrderedBulkOperation.handleWriteError (C:\Users\username\projectDirectory\node_modules\mongodb\lib\bulk\common.js:1352:9)
    at resultHandler (C:\Users\username\projectDirectory\node_modules\mongodb\lib\bulk\common.js:579:23)
    at handler (C:\Users\username\projectDirectory\node_modules\mongodb\lib\core\sdam\topology.js:943:24)
    at C:\Users\username\projectDirectory\node_modules\mongodb\lib\cmap\connection_pool.js:350:13
    at handleOperationResult (C:\Users\username\projectDirectory\node_modules\mongodb\lib\core\sdam\server.js:558:5)
    at MessageStream.messageHandler (C:\Users\username\projectDirectory\node_modules\mongodb\lib\cmap\connection.js:281:5)
    at MessageStream.emit (events.js:321:20)
    at processIncomingData (C:\Users\username\projectDirectory\node_modules\mongodb\lib\cmap\message_stream.js:144:12)
    at MessageStream._write (C:\Users\username\projectDirectory\node_modules\mongodb\lib\cmap\message_stream.js:42:5)
    at doWrite (_stream_writable.js:441:12)

假設集合名稱為user_demo並且只有 2 個字段 ( _id, name )

創建集合架構驗證器

db.createCollection("user_demo", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         title: "User Object Validation",
         required: [ "_id","name"],
         properties: {
            _id: {
               bsonType: "binData",
               description: "Unique identifier,I am using it instead of objectId for portibility",
               pattern: "^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
            },
            name: {
               bsonType: "string",
               description: "'name' must be a string and is required",
               maxLength: 50,
               minLength: 1
            }
         }
      }
   }
} )

在集合中插入數據

a) 如果你已經有一個uuid4

db.user_demo.insertOne({_id: UUID("a5750db3-1616-45a4-bf92-6a44c3e67342"), name:"shiva"})

b) 如果你想要隨機uuid4

db.user_demo.insertOne({_id: UUID(), name:"explore"})

使用 mongo 版本6.0.3測試

暫無
暫無

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

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