Victor Shelepen
Victor Shelepen

Reputation: 2256

Mongo ID to Meteor Mongo ID

I am writing a migration. I load a collection by mongodb because the collection definition has been deleted. I decompose data into SimpleSchema collections. I can not resave Mongo ObjectID because it is invalid. I tried the following variant. But it creates new. It can not recreate it.

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

Upvotes: 0

Views: 185

Answers (2)

Harry Adel
Harry Adel

Reputation: 1436

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

Upvotes: 1

Victor Shelepen
Victor Shelepen

Reputation: 2256

Mongo.ObjectID does not suggest Mongo ObjectID. It suggests only string or nothing.

Upvotes: 0

Related Questions