skip to Main Content

i have a document like this

{
  _id: ...
  deletedAt: null
  history: [
   {
     _id: ...
     name: ...
     deletedAt: null
   },
   {
     _id: ...
     name: ...
     deletedAt: null
   },
  ]
}

after saving a document i want to return the saved document without properties
deletedAt and history.$.deletedAt

i have post middleware

mySchema.post('save', function () {
  this.set('history.$[].deletedAt', undefined);
  this.set('history.$.deletedAt', undefined);
  this.set('deletedAt', undefined);
});

this middleware removes the deletedAt but it’s not removing history.$.deletedAt
when i do history.0.deletedAt this works , but only for the first item of the array. how to make this work for all elements of the array?

also in my model i have specified select: false like this

...
history: {
  type: [{
    ...
    deletedAt: { type: Date, default: null, select: false }
    ...
  }],
}
...

but any case history[n].deletedAt is being selected.

2

Answers


  1. Chosen as BEST ANSWER

    solved this way

    mySchema.post('save', function () {
      this.history.forEach((v, i) => this.set(`history.${i}.deletedAt`, undefined));
      this.set('deletedAt', undefined);
    });
    

  2. You can use Array.map()

    // Remove the deletedAt key from each object in the history array
    const historyWithoutDeletedAt = savedDoc.history.map(({ deletedAt, ...rest }) => rest);
    
    // Create a new object without the deletedAt key and with the updated history array
    const result = { ...savedDoc.toObject(), deletedAt: undefined, history: historyWithoutDeletedAt };
    
    // Return the new object
    return result;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search