猫鼬。删除模式中不存在的保存字段

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

我在 MongoDB 中保存了一个这样的文档:

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

这是 Mongoose 中的模式:

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

我希望在保存时,"admin" 字段已从文档中删除,这可能吗?我可以在 pre-save 事件中自动执行此操作吗?

谢谢。

好的,删除架构中不存在但文档中存在的字段的正确方法是:

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

你可以在你的中间件中使用它,在我的例子中是 pre-save 中间件。

我在 comment in this question 中找到了答案。

我还找不到自动化模式。