首页 > 解决方案 > Mongo ID 到 Meteor Mongo ID

问题描述

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

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

标签: mongodbmeteor

解决方案


Meteor's Mongo ID is inherently different from Mongo DB, so they're not interchangeable.

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

}

While Mongo's version:

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


推荐阅读