cdimascio / uuid-mongodb

📇 Generates and parses MongoDB BSON UUIDs
MIT License
101 stars 17 forks source link

Validation won't pass when using mongoDB validation schema #54

Open VicoF opened 3 years ago

VicoF commented 3 years ago

Hi, I'm trying to use the library to insert a new document that has a UUID as id in my collection. I would like this collection to have a validation schema to make sure that every ids of the documents inserted are UUIDs. However, when I'm specifying the BSON type 'object', the validation won't pass.

I have seen in the examples that I could use mongoose, but I would prefer the validation to be perform at the database level. Do you have any idea of how I could make this work or any explanation of why it is not working? Thank you!

Db migration code:

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

module.exports = {
  async up(db) {

    await db.createCollection("itemCategories", {
      validator: {
        $jsonSchema: {
          required: ["name", "_id"],
          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");
  }
};

And the error I get

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)