猫鼬。删除架构中不存在的保存字段

che*_*xis 2 mongoose mongodb node.js mongoose-schema

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

{
  title: 'title',
  author: 'author name',
  body: 'the body',
  admin: 'admin user'
}
Run Code Online (Sandbox Code Playgroud)

这是猫鼬的模式:

var blogSchema = new Schema({
  title:  String,
  author: String,
  body:   String
});
Run Code Online (Sandbox Code Playgroud)

我想保存后,就从文档中删除了“ admin”字段,这可能吗?我可以在事件预保存时自动执行此操作吗?

谢谢。

che*_*xis 5

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

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

您可以在中间件中使用它,例如,在保存前的中间件中使用它。

我在这个问题评论中找到了答案。

我还找不到自动模式。