mongodb - Mongo ID 到 Meteor Mongo ID
问题描述
我正在写一个迁移。我通过 mongodb 加载了一个集合,因为集合定义已被删除。我将数据分解为 SimpleSchema 集合。我无法重新保存 Mongo ObjectID,因为它无效。我尝试了以下变体。但它创造了新的。它无法重新创建它。
const meteorID = (_id) => new Mongo.ObjectID(_id)
解决方案
Meteor's Mongo ID is inherently different from Mongo DB, so they're not interchangeable.
MongoID._looksLikeObjectID = str => str.length === 24 && str.match(/^[0-9a-f]*$/);
MongoID.ObjectID = class ObjectID {
constructor (hexString) {
//random-based impl of Mongo ObjectID
if (hexString) {
hexString = hexString.toLowerCase();
if (!MongoID._looksLikeObjectID(hexString)) {
throw new Error('Invalid hexadecimal string for creating an ObjectID');
}
// meant to work with _.isEqual(), which relies on structural equality
this._str = hexString;
} else {
this._str = Random.hexString(24);
}
}
equals(other) {
return other instanceof MongoID.ObjectID &&
this.valueOf() === other.valueOf();
}
toString() {
return `ObjectID("${this._str}")`;
}
clone() {
return new MongoID.ObjectID(this._str);
}
typeName() {
return 'oid';
}
getTimestamp() {
return Number.parseInt(this._str.substr(0, 8), 16);
}
valueOf() {
return this._str;
}
toJSONValue() {
return this.valueOf();
}
toHexString() {
return this.valueOf();
}
}
While Mongo's version:
https://docs.mongodb.com/manual/reference/method/ObjectId/ https://github.com/williamkapke/bson-objectid
推荐阅读
- c# - SignalR Core 抛出已处理的异常
- indexeddb - 为什么 IndexedDB 挂起?
- java - 单元测试:一次测试中有 2 个场景?
- symfony - API PLATFORM ApiTestCase 身份验证发送意外响应
- r - R中y轴的不同间隔
- python - TensorFlow 1.x 上用于优化的 TFLiteConverter 参数
- python - 如何仅获取父目录的名称,而不是完整路径?
- debugging - 如何在使用 Segger J-link pro 和 Stm32cubeIDE 进行调试期间暂停看门狗计数器
- java - 如何找出“系统定义的”套接字超时和连接超时是什么?
- python - 如何使用python从PDF中提取文本、表格和图像