有没有一种方法可以使用mongo的验证器来验证插入到mongoDB中的UUID?

t40tm48m  于 2023-01-01  发布在  Go
关注(0)|答案(1)|浏览(141)

我正在使用migrate-mongo来管理我的数据库迁移,并且我正在尝试创建一个新的迁移,该迁移将创建一个带有验证器的集合,并在其中插入值。我希望为_id属性使用UUID,并且我正在使用uuid-mongodb库来生成它。我的问题是我无法在验证器中设置my _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)
esyap4oy

esyap4oy1#

假设集合名称为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进行测试

相关问题