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
  • 13,889
  • 17
  • 74
  • 125

3 Answers3

8

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
  • 13,889
  • 17
  • 74
  • 125
0

While the suggested answer might work (didn't test myself), there's a more versatile solution to allow multiple fields and documents with one call:

const fields = ["admin"];
const unset = fields.reduce(
  (acc, field) => ({
    ...acc,
    [field]: 1,
  }),
  {}
);

YourModel.collection.updateMany(query, { $unset: unset });
Shining Love Star
  • 5,734
  • 5
  • 39
  • 49
0

Try turning off strict mode in your update and it should work though:

User.update({}, {$unset: {someField: 1}}, {multi: true, strict: false});

original answer was taken from this issue

Jubair
  • 11
  • 2