将mongoose设置为允许null而不破坏验证



以下是我的应用程序的工作方式。用户首次使用谷歌登录。我们从他们的谷歌账户中获得以下数据:

  1. 给定名称
  2. 姓氏
  3. 电子邮件ID

我们希望使用此信息调用我们的API(POST请求(来创建用户配置文件。

我们发送的数据是

{
firstName: firstName ,
lastName: lastName, 
email: email
}

这就是问题的根源。用户配置文件有许多字段,其中一个字段是名称。当用户第一次登录时,我们不知道他们的名称。

我们的数据库使用MongoDB。所以我们使用Mongoose来建立连接。在Mongoose模型中,我们为我们的模式添加了一些验证。指定是必填字段。它的长度应至少为一个字符,最多为40个字符。如果我们将指定设置为null,则验证将失败。

有没有办法允许Mongoose中的必填字段为null?

您可以向它传递一个函数:,而不是将required设置为true或false

const user = new Schema({
designation: {
type: String,
minLength: 1,
maxLength: 40,
required: function() {
// Rather than checking a stored variable, you could check
// static functions on the model, a custom value on the 
// instance that isn't persisted, etc.
return this.hasLoggedInAtLeastOnce === true;
// If this function returns true, the field is required.
}
}
hasLoggedInAtLeastOnce: {
type: Boolean,
}
});

最新更新