Meteor Mongo BulkOp 将 ObjectID 转换为普通对象

Meteor Mongo BulkOp turning ObjectID into plain object

在使用 Meteor 时,我有时会访问底层节点 Mongo 驱动程序,这样我就可以进行批量更新和插入。

const bulk = Coll.rawCollection().initializeOrderedBulkOp();

bulk.insert({key_id: Mongo.Collection.ObjectID()}); // note key_id is an ObjectID
...

bulk.execute();

但是当我在插入后查看数据库时,key_id 字段的值最终成为纯子文档 {_str: '...'}

有没有什么方法可以在 Node 的 Mongo 库中使用批量操作(无论 Meteor 使用什么)并保持 ObjectID 为 Mongo 的 ObjectID 类型?

(有很多帖子介绍了不同 ID 类型的性质,并解释了 Minimongo 等。我对将 ObjectID 转换为普通对象的批量操作以及解决该问题特别感兴趣。)

来自

On a native method you would actually need to grab the native implementation. You should be able to access from the loaded driver through MongoInternals [...]

Mongo.Collection.ObjectID is not a plain ObjectId representation, and is actually a complex object for Meteor internal use. Hence why the native methods don't know how to use the value.

因此,如果您有一些 ObjectId 字段,并且您正在使用 Meteor Collection rawCollection 的某些方法(例如,

  • .distinct
  • .aggregate
  • .initializeOrderedBulkOp
  • .initializeUnorderedBulkOp

),您需要使用

转换 ObjectId
const convertedID = new MongoInternals.NpmModule.ObjectID(
  originalID._str
);
// then use in one of the arguments to your function or something
const query = {_id: convertedID};

在对它们调用方法之前。