mongoose 在父模式中设置默认值

rnmwe5a2  于 2023-06-23  发布在  Go
关注(0)|答案(1)|浏览(146)

我有嵌套模式。我想在父模式中设置子模式的默认值。下面是我的模式和我尝试过的:

const daySchema = mongoose.Schema({
    day: String,
    am1: periodSchema,
    am2: periodSchema,
    am3: periodSchema,
    pm1: periodSchema,
    pm2: periodSchema,
    pm3: periodSchema,
});

const programoSchema = mongoose.Schema({
    monday: {
        type: daySchema,
        default: {
            ...daySchema,
            day: "Pazartesi",
        },
    },
    tuesday: daySchema,
    wednesday: daySchema,
    thursday: daySchema,
    friday: daySchema,
});

但它不起作用。我该怎么办?先谢谢你了。

2uluyalo

2uluyalo1#

通过简单地删除...daySchema问题将得到解决。

monday: {
        type: daySchema,
        default: {
            day: "Pazartesi",
        },
    },

但是,当默认值是动态的,就像代码中一样,更好的解决方案是创建一个函数,它接受默认值并返回一个模式,就像下面的代码一样。

const periodSchema = mongoose.Schema({
  hour: {
    type: String,
    default: "00:00"
  }
});

const daySchema = function (defaultDay) { 
                      return {
                          type: new mongoose.Schema({
                                      day: String,
                                      am1: periodSchema,
                                      am2: periodSchema,
                                      am3: periodSchema,
                                      pm1: periodSchema,
                                      pm2: periodSchema,
                                      pm3: periodSchema,
                                  }),
                          default: {
                              day: defaultDay
                          }
                      }
}

const programoSchema = mongoose.Schema({
    monday: daySchema("Pazartesi"),
    tuesday: daySchema(),
    wednesday: daySchema(),
    thursday: daySchema(),
    friday: daySchema(),
});

const Program = mongoose.model("programs", programoSchema);

console.log(new Program());
<script src="https://cdn.jsdelivr.net/npm/mongoose@7.2.3/dist/browser.umd.min.js"></script>

相关问题