Skip to content

collection.create() returns BSON ObjectId for objectId fields instead of decoded hex string #577

@RaschidJFR

Description

@RaschidJFR

Package and version

@prisma-next/mongo@0.4.4

What happened?

For objectId fields, the row returned by collection.create(...) contains a raw BSON ObjectId, while the same row read back via .where(...).first() / .all().toArray() contains a hex string.

The static row type (InferRootRow<Contract, Model>) declares the field as string in both cases, so the create() result silently mismatches its declared type.

What did you expect to happen?

create() should return the row in the same shape as reads — with objectId fields decoded to hex string via the mongoObjectIdCodec's decode step — so that created._id === (await coll.where({ _id: created._id }).first())._id.

Minimal reproduction

// contract.ts
const Reaction = model('Reaction', {
  collection: 'reactions',
  fields: {
    _id: field.objectId(),
    user: field.objectId(),
    article: field.string(),
    reaction: field.int32(),
  },
});

// test
const created = await db.orm.reactions.create({
  user: '6a0e167c6b453dd74e2662a8',
  article: 'abc',
  reaction: 1,
});
const fetched = await db.orm.reactions.where({ _id: created._id }).first();

console.log(typeof created._id);  // 'object' (BSON ObjectId)
console.log(typeof fetched!._id); // 'string'
expect(created._id).toBe(fetched!._id); // fails```

Environment

  • Node: 22.x
  • OS: macOS
  • Package manager: npm 10.x
  • Database: MongoDB 8.x (replica set via mongodb-runner)

Additional context

Codec definition that confirms the intended decoded shape is string:

// @prisma-next/adapter-mongo/src/core/codecs.ts
export const mongoObjectIdCodec = mongoCodec({
  typeId: MONGO_OBJECTID_CODEC_ID,
  targetTypes: ['objectId'],
  traits: ['equality'],
  decode: (wire: ObjectId) => wire.toHexString(),
  encode: (value: string) => new ObjectId(value),
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingneeds-triageAwaiting maintainer triage

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions