具有嵌套可选对象的Mongoose模式 [英] Mongoose Schema with nested optional object

查看:63
本文介绍了具有嵌套可选对象的Mongoose模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下架构:

{
  data1: String,
  nested: {
    nestedProp1: String,
    nestedSub: [String]
  }
}

当我执行new MyModel({data1: 'something}).toObject()时,将显示新创建的文档,如下所示:

When I do new MyModel({data1: 'something}).toObject() shows the newly created document like this:

{
  '_id' : 'xxxxx',
  'data1': 'something',
  'nested': {
    'nestedSub': []
  }
}

即嵌套的文档是使用空数组创建的.

I.e. the nested document is created with the empty array.

如何使嵌套"成为完全可选的-如果输入数据中未提供嵌套",则完全不创建?

How do I make "nested" to be fully optional - i.e. not created at all if it is not provided on the input data?

不想为嵌套"使用单独的架构,不需要这种复杂性.

I do not want to use a separate schema for the "nested", no need of that complexity.

推荐答案

以下架构可以满足我的原始要求:

The following schema satisfies my original requirements:

{
  data1: String,
  nested: {
    type: {
       nestedProp1: String,
       nestedSub: [String]
    },
    required: false
  }
}

由此,如果未指定子文档,则会使用缺少"子文档来创建新文档.

With this, new docs are created with "missing" subdocument, if one is not specified.

这篇关于具有嵌套可选对象的Mongoose模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆