我正在使用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)
1条答案
按热度按时间esyap4oy1#
假设集合名称为
user_demo
,并且只有2个字段(_id, name
)创建集合架构验证器
在集合中插入数据
a)如果您已经有
uuid4
B)如果您想要随机
uuid4
使用mongo版本
6.0.3
进行测试