使用 MongooseJS 将 Mongodb _id 更改为 BSON UUID 以供参考
Using MongooseJS to Changing Mongodb _id to BSON UUID for ref
我目前使用 MongooseJS 将我的每个集合的“_id”更改为 BSON UUID。最重要的是,我使用虚拟到 "id" 将“_id”转换为其等效的字符串。它工作得很好,给我带来了使用 UUID 作为“_id”的好处,而不是将它存储为浪费磁盘资源的字符串。
这是一段代码,展示了这是如何完成的
const uuid = require("uuid-mongodb");
require("mongoose-uuid2")(mongoose);
let schema_options = {
"id": false,
"toObject": {
"getters": true,
"virtuals": true
},
"toJSON": {
"getters": true,
"virtuals": true,
"transform"(doc, ret) {
delete ret._id;
}
} };
let schema = new Schema(
{
"_id": {
"type": UUID,
"default": uuid.v4,
"required": true
},
"code": {
"type": String,
"required": true,
"unique": true
},
"name": {
"type": String,
"required": true
}
},
schema_options);
schema.virtual("id").get(function() {
return uuid.from(this._id).toString();
});
schema.virtual("id").set(function(uuid_string) {
this._id = uuid.from(uuid_string);
});
但是,如果我将 "ref" 添加到另一个集合中,就像
schema.add({
"test_references": {
"type": [
{
"type": mongoose.Types.UUID,
"ref": "test_references"
}
],
"required": true
}
});
我得到了 BSON UUID 的哈希表示。有没有办法在获取操作期间使 MongooseJS 将这些引用显示为 UUID 字符串表示
即- 我期待这个“104e0f2e-3b54-405b-ba81-e87c5eb9f263”但是得到这个 "EE4PLjtUQFu6geh8XrnyYw=="
注意::如果此论坛不正确post,请告诉我,我会立即将其移至正确的论坛
经过更多研究,我能够对返回值应用转换。
这看起来像下面这样:
this.schema.options.toJSON.transform = function(doc, ret, option) {
let items = [];
delete ret._id;
ret.items.forEach((item) => {
items.push(mongoose.uuid.from(item).toString());
});
ret.items = items;
return ret;
};
浏览数组中的所有项目并不理想,但这是我在研究中能找到的最好的
我目前使用 MongooseJS 将我的每个集合的“_id”更改为 BSON UUID。最重要的是,我使用虚拟到 "id" 将“_id”转换为其等效的字符串。它工作得很好,给我带来了使用 UUID 作为“_id”的好处,而不是将它存储为浪费磁盘资源的字符串。
这是一段代码,展示了这是如何完成的
const uuid = require("uuid-mongodb");
require("mongoose-uuid2")(mongoose);
let schema_options = {
"id": false,
"toObject": {
"getters": true,
"virtuals": true
},
"toJSON": {
"getters": true,
"virtuals": true,
"transform"(doc, ret) {
delete ret._id;
}
} };
let schema = new Schema(
{
"_id": {
"type": UUID,
"default": uuid.v4,
"required": true
},
"code": {
"type": String,
"required": true,
"unique": true
},
"name": {
"type": String,
"required": true
}
},
schema_options);
schema.virtual("id").get(function() {
return uuid.from(this._id).toString();
});
schema.virtual("id").set(function(uuid_string) {
this._id = uuid.from(uuid_string);
});
但是,如果我将 "ref" 添加到另一个集合中,就像
schema.add({
"test_references": {
"type": [
{
"type": mongoose.Types.UUID,
"ref": "test_references"
}
],
"required": true
}
});
我得到了 BSON UUID 的哈希表示。有没有办法在获取操作期间使 MongooseJS 将这些引用显示为 UUID 字符串表示
即- 我期待这个“104e0f2e-3b54-405b-ba81-e87c5eb9f263”但是得到这个 "EE4PLjtUQFu6geh8XrnyYw=="
注意::如果此论坛不正确post,请告诉我,我会立即将其移至正确的论坛
经过更多研究,我能够对返回值应用转换。
这看起来像下面这样:
this.schema.options.toJSON.transform = function(doc, ret, option) {
let items = [];
delete ret._id;
ret.items.forEach((item) => {
items.push(mongoose.uuid.from(item).toString());
});
ret.items = items;
return ret;
};
浏览数组中的所有项目并不理想,但这是我在研究中能找到的最好的