mongodb模式如何设置子文档数组的默认值?

zer*_*r09 4 arrays mongodb mongoose-schema

示例我有这个架构。

{
  field1: {
    type: String,
    trim: true
  },
  field2: [{
    subField1: {
      type: String,
    },
    subField2: {
      type: Number,
      default: 0
    }
  }]
}
Run Code Online (Sandbox Code Playgroud)

field2如果我刚刚field1在文档插入中提供了,我应该如何设置模式的默认值?

示例 如果我只是插入{field1: "sample string data"},则 上的值field2是一个空数组。

Sar*_*ana 5

你可以尝试这个吗?,用于type指定模式和default默认值

const TesterSchema = new Schema({  
      field1: {
        type: String,
        trim: true
      },
      field2: {
        type : [{
          subField1: {
            type: String                  
          },
          subField2: {
            type: Number                  
          }
      }],
      default :[{subField2 : '0'}]
    }
  }
);
Run Code Online (Sandbox Code Playgroud)

例子

Tester.create({field1 : 'testing'}, function(err,doc){
    if(err) console.log(err)
    console.log(doc)
})
Run Code Online (Sandbox Code Playgroud)

控制台输出

Mongoose: testerzz.insert({ field1: 'testing', _id: ObjectId("5a6ae40a351d4254c6e0fdc2"), field2: [ { subField2: 0, _id: ObjectId("5a6ae40a351d4254c6e0fdc1") } ], __v: 0 })
{ __v: 0,
  field1: 'testing',
  _id: 5a6ae40a351d4254c6e0fdc2,
  field2: [ { subField2: 0, _id: 5a6ae40a351d4254c6e0fdc1 } ] }
Run Code Online (Sandbox Code Playgroud)

蒙戈命令行界面

> db.testerzz.find({_id: ObjectId("5a6ae40a351d4254c6e0fdc2")}).pretty()
{
    "_id" : ObjectId("5a6ae40a351d4254c6e0fdc2"),
    "field1" : "testing",
    "field2" : [
        {
            "subField2" : 0,
            "_id" : ObjectId("5a6ae40a351d4254c6e0fdc1")
        }
    ],
    "__v" : 0
}
> 
Run Code Online (Sandbox Code Playgroud)