具有嵌套可选对象的Mongoose Schema

时间:2022-04-04 19:42:40

Using the following schema:

使用以下架构:

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

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

当我做新的MyModel({data1:'something})。toObject()显示新创建的文档,如下所示:

{
  '_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.

我不想为“嵌套”使用单独的模式,不需要那种复杂性。

3 个解决方案

#1


8  

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.

有了这个,如果没有指定,则使用“missing”子文档创建新文档。

#2


1  

You can use strict: false

你可以使用strict:false

new Schema({
    'data1': String,
    'nested': {
    },
}, 
{
    strict: false
});

And then the schema is fully optional. To set only nested as fully optional maybe you can do something like:

然后架构是完全可选的。要仅将嵌套设置为完全可选,您可以执行以下操作:

new Schema({
    'data1': String,
    'nested': new Schema({}, {strict: false})
});

But I have never tried

但我从未尝试过

#3


0  

A solution without additional Schema object could use a hook like the following

没有其他Schema对象的解决方案可以使用如下所示的钩子

MySchema.pre('save', function(next) {
  if (this.isNew && this.nested.nestedSub.length === 0) {
      this.nested.nestedSub = undefined;
  }
  next();
});

#1


8  

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.

有了这个,如果没有指定,则使用“missing”子文档创建新文档。

#2


1  

You can use strict: false

你可以使用strict:false

new Schema({
    'data1': String,
    'nested': {
    },
}, 
{
    strict: false
});

And then the schema is fully optional. To set only nested as fully optional maybe you can do something like:

然后架构是完全可选的。要仅将嵌套设置为完全可选,您可以执行以下操作:

new Schema({
    'data1': String,
    'nested': new Schema({}, {strict: false})
});

But I have never tried

但我从未尝试过

#3


0  

A solution without additional Schema object could use a hook like the following

没有其他Schema对象的解决方案可以使用如下所示的钩子

MySchema.pre('save', function(next) {
  if (this.isNew && this.nested.nestedSub.length === 0) {
      this.nested.nestedSub = undefined;
  }
  next();
});