首页 > 解决方案 > Mongoose 更新不在架构中的属性

问题描述

我正在尝试设置一个 CRUD 应用程序,它允许人们将某些服务标记为完整或不完整。
随着时间的推移,服务可能会发生变化,有些是添加的,有些是删除的,所以我试图弄清楚我是否可以从架构中删除服务,但保留旧文档更新这些服务的能力。

这是我的架构的相关部分:

  services: {
    tom: {
      name: {
        type: String,
        default: "Top of Mind",
        required: true
      },
      status: {
        type: Boolean,
        default: false,
        required: true
      }
    },
    two: {
      name: {
        type: String,
        default: "Service Two",
        required: true
      },
      status: {
        type: Boolean,
        default: false,
        required: true
      }
    },
    three: {
      name: {
        type: String,
        default: "Service Three",
        required: true
      },
      status: {
        type: Boolean,
        default: false,
        required: true
      }
    }
  }

我将 strict 属性设置为 false 以希望更新任何其他服务,即使它不存在于架构中。例如,在 Mongo Atlas 集合中,我手动将服务添加到一个文档,如下所示:

test: {
  name: "Test Service", 
  status: false
}

这在读取数据时工作正常,并且在对请求执行更新直到我尝试更改 test.status 时出现。
返回整个文档,包括服务下的测试对象,但doc.services.test未定义,这意味着我无法编辑“测试”的状态。

编辑:这是查找文档时返回的服务对象:

{ 
  tom: { name: 'Top of Mind', status: true },   
  two: { name: 'Service Two', status: true },   
  three: { name: 'Service Three', status: true },   
  test: { name: 'Service Test', status: false } 
} 

doc.services.test 返回未定义

这里是否有解决方法,或者“测试”服务是否需要存在于模式中才能更新它?

标签: javascriptmongodbobjectmongoose

解决方案


推荐阅读