4

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.

chemitaxis
  • 11,583
  • 14
  • 62
  • 117

1 Answers1

7

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.

Community
  • 1
  • 1
chemitaxis
  • 11,583
  • 14
  • 62
  • 117