adonis-mongodb icon indicating copy to clipboard operation
adonis-mongodb copied to clipboard

Spread operator brings unwanted data

Open maasencioh opened this issue 2 years ago • 6 comments

After #112 a spread operator on .all() returns inner state metadata ($isPersisted, $isLocal, etc) instead of the current data.

const events =  (await eventCursor.all()).map(({ _id, ...rest }) => ({ ... rest, id: _id }));
/*
[
  {
     '$isPersisted': true,
     '$isLocal': false,
     '$isDeleted': false,
     '$collection': Collection { s: [Object] },
     '$originalData': {
       _id: new ObjectId("6127519d992a7f508fe38282"),
       createdAt: 2021-08-26T08:32:29.629Z,
       updatedAt: 2021-08-26T08:32:29.629Z,
       topic: 'b1505',
       data: [Object],
       processors: []
     },
     '$currentData': {
       _id: new ObjectId("6127519d992a7f508fe38282"),
       createdAt: 2021-08-26T08:32:29.629Z,
       updatedAt: 2021-08-26T08:32:29.629Z,
       topic: 'b1505',
       data: [Object],
       processors: []
     },
     '$options': { collection: [Collection], session: undefined }
     id: "6127519d992a7f508fe38282",
   },
]
*/

maasencioh avatar Sep 21 '21 09:09 maasencioh

Models are proxies on the data that currently only intercept get and set operations: https://github.com/zakodium/adonis-mongodb/blob/main/src/Model/proxyHandler.ts

I think we could support spreading with an ownKeys interceptor. Do you expect that {...modelInstance} returns a shallow copy of $currentData ?

targos avatar Sep 21 '21 10:09 targos

Daniel's idea: make {...modelInstance} similar to instance.toJSON()

targos avatar Sep 21 '21 12:09 targos

Related: https://github.com/zakodium/adonis-mongodb/issues/72#issuecomment-876122196

If we implement the public $attributes field, it will be possible to do {...instance.$attributes}

targos avatar Sep 21 '21 12:09 targos

In the mean time, I will make ownKeys throw so that spreading by mistake doesn't do something unexpected

targos avatar Sep 21 '21 12:09 targos

Sorry, I think that the natural behavior for me is to have what's inside $currentData, what could be the difference with the toJSON result?

maasencioh avatar Sep 21 '21 12:09 maasencioh

At the moment, there is no difference (toJSON returns $currentData). But one of the features of Lucid that I want to implement is field serializers. toJSON would call the serializers.

targos avatar Sep 21 '21 12:09 targos