【问题标题】:Mongoose. Remove fields on save that are not present in schema猫鼬。删除模式中不存在的保存字段
【发布时间】:2017-09-14 15:28:37
【问题描述】:

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

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

这是 Mongoose 中的架构:

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

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

谢谢。

【问题讨论】:

  • 你能说明你是如何保存博客的吗?理想情况下,如果未在架构中定义管理字段,则不应保存它
  • 所以,您需要将保存的文档返回给客户端,但您不想显示管理字段,对吧?
  • 不,文档之前是通过其他机制保存在数据库中的,现在不需要admin字段...

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:

好的,删除Schema中不存在而文档中存在的字段的正确方法是:

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

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

我在comment 在这个question 中找到了答案。

我还找不到自动化模式。

【讨论】:

    猜你喜欢
    • 2019-04-13
    • 1970-01-01
    • 2017-06-12
    • 2018-08-27
    • 1970-01-01
    • 2020-09-05
    • 2014-08-03
    • 2016-11-18
    • 1970-01-01
    相关资源
    最近更新 更多