具有必需字段的嵌套可选对象的Mongoose Schema

时间:2021-08-22 18:23:56

I'd like to create a Mongoose Schema that validates the object below with the following restrictions:

我想创建一个Mongoose Schema,它使用以下限制验证下面的对象:

  • field2 is optional (0-1 relationship),
  • field2是可选的(0-1关系),

  • field2.type is required if field2 exists (notice that the name of the field is "type" as mongoose reserved word for type definitions),
  • 如果field2存在,则需要field2.type(注意字段的名称是“type”作为类型定义的mongoose保留字),

  • field2 and the the base object must be in the same document.
  • field2和基础对象必须位于同一文档中。

Code example

{
  field1: "data",
  field2: {
    type: "data",
    data: "data"
  }
}

Thanks in advance.

提前致谢。

2 个解决方案

#1


1  

You can refer to this answer:

你可以参考这个答案:

{
  field1: "your data",
  field2:
  {
    type:
    {
      "your data"
    },
    required:false
  }
}

So an example would be:

所以一个例子是:

{
  field1: String,
  field2:
  {
    type:
    {
      nestedField1:{type:String,required:true},
      nestedField2:String
    },
    required:false
  }
}

if field2 exists then nestedField1 would be required.

如果field2存在则需要nestedField1。

#2


-1  

you may mean something like this:

你可能意思是这样的:

var Field2Schema = new mongoose.Schema({
  type: { type: String, required: true },
  data: String
});

var MainSchema = new mongoose.Schema({
  field1: String,
  field2: Field2Schema
});

#1


1  

You can refer to this answer:

你可以参考这个答案:

{
  field1: "your data",
  field2:
  {
    type:
    {
      "your data"
    },
    required:false
  }
}

So an example would be:

所以一个例子是:

{
  field1: String,
  field2:
  {
    type:
    {
      nestedField1:{type:String,required:true},
      nestedField2:String
    },
    required:false
  }
}

if field2 exists then nestedField1 would be required.

如果field2存在则需要nestedField1。

#2


-1  

you may mean something like this:

你可能意思是这样的:

var Field2Schema = new mongoose.Schema({
  type: { type: String, required: true },
  data: String
});

var MainSchema = new mongoose.Schema({
  field1: String,
  field2: Field2Schema
});