默认值不添加到猫鼬模型

Default values not adding to mongoose Model

所以这是我为用户准备的架构示例。

    id: String,
    email: String,
    slug: {
        type: Object,
        phrase: {type: String, default: null},
    },

当我想定义一个新用户并保存该用户时,我会执行以下操作;

const newUser = new User({
   id: 123,
   username: "CoolUser",
   email: "BillGates@google.com"
});
                
newUser.save();

但这不会保存“slug”对象,据我了解,由于我为其设置了默认值,因此它会自动填充该默认值。我该怎么做才能让它自动生成而无需在保存用户时再次定义整个架构?

试试这个:

const subschema = new Schema({
  phrase: {type: String, default: null},
}, { _id: false });

在您的原始架构中:

  id: String,
  email: String,
  slug: {
    type: subschema,
    default: () => ({})
  },

这应该可以解决问题。

您应该为 slug 属性 添加默认值,而不是为他的 sub-property 添加默认值。尝试像这样更改架构:

slug: {
  type: {
    phrase: { type: String },
  },
  default: {
    phrase: null 
  },
},
const User = new Schema({
    id: String,
    about: {
        bio: String,
        location: String,
        website: String,
        discord: String,
        twitter: String,
        default: {
            bio: "This is a default bio.",
            location: "",
            website: "",
            discord: "",
            twitter: "",
        }
    }
})

好的,这是示例,为了方便起见,我从中删除了一些内容,基本上如您所见,我希望 bio 默认为:This is a default bio.

但是,我收到以下错误:

    throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
    ^

TypeError: Invalid schema configuration: `This is a default bio.` is not a valid type at path `about.default.bio`. See bit ly / mongoose-schematypes for a list of valid schema types.