loopbackio / loopback-next

LoopBack makes it easy to build modern API applications that require complex integrations.
https://loopback.io
Other
4.95k stars 1.07k forks source link

Robust handling of ObjectID type for MongoDB #3720

Open bajtos opened 5 years ago

bajtos commented 5 years ago

MongoDB is tricky - see https://github.com/strongloop/loopback-next/issues/1875

As a result, both PK and FK properties must use ObjectID as the type, and coercion must be applied where necessary.

Ideally, I'd like LB4 to define MongoDB PK and FKs as follows:

Even better, dataType: 'ObjectID' should be automatically applied by the connector for PK and FKs referencing ObjectID PKs.

For example:

@model()
class Product {
  @property({
    type: 'string',
    generated: true,
    // ^^ implies dataType: 'ObjectID'
  })
  id: string;

  @property({
    type: 'string',
    references: {
      model: () => Category,
      property: 'id',
    },
    // ^^ implies dataType: 'ObjectID' when Category is attached to MongoDB
  })
  categoryId: string;
}

For v1, I suppose we can ask developers to provide dataType manually.

@model()
class Product {
  @property({
    type: 'string',
    generated: true,
    mongodb: {dataType: 'ObjectID'},
  })
  id: string;

  @property({
    type: 'string',
    mongodb: {dataType: 'ObjectID'},
  })
  categoryId: string;
}

With this setup in place, id and categoryId properties should be always returned as strings from DAO and connector methods.

Related discussions

Acceptance criteria

Tasks

sushant022 commented 3 years ago

Loopback 3 has AccessToken _id of type string. I have an app using db generated by lb3 and reuse in an lb4 app. How can i use _id as type string?

Barnette-ao commented 2 years ago

there is something confused by setting mongodb: {dataType: 'ObjectID'}, in my loopback4 application.

When the MongoDB connector returns data from database, it converts ObjectID values to strings.

as above say, if I get a model User,and I call the this.userRepository.create(user),it will return a User object instance,UserInstance.

Expect

according to my understand of citing criteria,I expect

typeof(UserInstance.id) == string

Actural

typeof(UserInstance) == object

this make me confused about the criteria cited above.

please give me some instruction.

@bajtos