【问题标题】:Mongo ID to Meteor Mongo IDMongo ID 到 Meteor Mongo ID
【发布时间】:2021-08-28 04:26:34
【问题描述】:

我正在编写迁移。我通过 mongodb 加载了一个集合,因为集合定义已被删除。我将数据分解为 SimpleSchema 集合。我无法重新保存 Mongo ObjectID,因为它无效。我尝试了以下变体。但它创造了新的。它无法重新创建它。

const meteorID = (_id) => new Mongo.ObjectID(_id)

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    Meteor 的 Mongo ID 本质上与 Mongo DB 不同,因此它们不可互换。

    https://github.com/meteor/meteor/blob/2d41716645c75c5bc2ef37f306ef87c00b982d16/packages/mongo-id/id.js#L8

    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();
      }
    
    }
    

    而 Mongo 的版本:

    https://docs.mongodb.com/manual/reference/method/ObjectId/ https://github.com/williamkapke/bson-objectid

    【讨论】:

    • 作为旁注,它们在一方面是可互换的:Meteor Mongo Id 十六进制字符串与本机 Mongo ID 的长度相同。因此,您需要从 mongo id 中“提取”十六进制字符串,然后您可以将其保存为 _id 值。 Meteor Mongo Collections 构造函数通过idGeneration 选项支持这一点。
    【解决方案2】:

    Mongo.ObjectID 不建议使用 Mongo ObjectID。它建议只有字符串或什么都没有。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      • 2020-10-16
      • 2018-12-06
      • 2014-03-09
      • 1970-01-01
      相关资源
      最近更新 更多