Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose. Remove fields on save that are not present in schema

I have a doc saved in MongoDB like this:

{
  title: 'title',
  author: 'author name',
  body: 'the body',
  admin: 'admin user'
}

And this is the schema in Mongoose:

var blogSchema = new Schema({
  title:  String,
  author: String,
  body:   String
});

I would like that on save, the "admin" field was removed from the doc, is this possible? Can I automatize this in event pre-save?

Thanks.

like image 683
chemitaxis Avatar asked Mar 09 '23 07:03

chemitaxis


1 Answers

Ok, the correct way of removing a field that is not present in the Schema and is present in the document is:

doc.set('field', undefined, { strict: false }) // strict is default true, you need to add if you are using strict mode

You can use it for example in your middlewares, in my case in the pre-save middleware.

I found the answer in a comment in this question.

I can't find an automatize mode yet.

like image 68
chemitaxis Avatar answered Mar 12 '23 10:03

chemitaxis