Skip to content

Model.toObject() should preserve prototypes (e.g. Date and ObjectID values) #3607

@bajtos

Description

@bajtos

Suggestion

ATM, toObject() method is implemented via toJSON and thus converts object values to JSON representation. This is problematic e.g. for Date and ObjectID values.

I am proposing to modify toObject() to preserve type of Date, ObjectID and other non-model values. Of course, if a model instance has a property set to a value of another Model, that property must be recursively converted via toObject to a plain object.

Use Cases

Consider the following test demonstrating the problem:

@model()
class Order extends Entity {
  @property({
      type: 'string',
      id: true,
      generated: true,
    })
    id: string;

    @property()
    createdAt: Date;
}

const orderRepo = // ...;
const DATE = new Date(...);
const created = orderRepo.create({
  createdAt: DATE;
});

expect(created.toObject()).to.deepEqual({
  id: created.id,
  createdAt: DATE,
});

The assertion above fails now.

Examples

The test example above should pass.

Acceptance criteria

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions