一尘不染

mongoose:扩展架构

node.js

目前,我有两个几乎相同的架构:

var userSchema = mongoose.Schema({

    email: {type: String, unique: true, required: true, validate: emailValidator},
    passwordHash: {type: String, required: true},

    firstname: {type: String, validate: firstnameValidator},
    lastname: {type: String, validate: lastnameValidator},
    phone: {type: String, validate: phoneValidator},

});

var adminSchema = mongoose.Schema({

    email: {type: String, unique: true, required: true, validate: emailValidator},
    passwordHash: {type: String, required: true},

    firstname: {type: String, validate: firstnameValidator, required: true},
    lastname: {type: String, validate: lastnameValidator, required: true},
    phone: {type: String, validate: phoneValidator, required: true},

});

它们的唯一区别在于验证:用户不需要名字,姓氏或电话。但是,管理员必须定义这些属性。

不幸的是,上面的代码不是很干,因为它们几乎相同。因此,我想知道是否有可能adminSchema基于userSchema。例如:

var adminSchema = mongoose.Schema(userSchema);
adminSchema.change('firstname', {required: true});
adminSchema.change('lastname', {required: true});
adminSchema.change('phone', {required: true});

显然,这只是伪代码。这样的事情可能吗?

另一个非常相似的问题是,是否有可能基于另一个创建新的架构,并为其添加更多属性。例如:

var adminSchema = mongoose.Schema(userSchema);
    adminSchema.add(adminPower: Number);

阅读 246

收藏
2020-07-07

共1个答案

一尘不染

在其他地方,有人建议使用utils.inherits扩展架构。另一种简单的方法是使用设置简单地设置对象并从中创建模式,如下所示:

var settings = {
  one: Number
};

new Schema(settings);

settings.two = Number;
new Schema(settings);

不过,这有点丑陋,因为您要修改同一对象。我也希望能够扩展插件和方法等。因此,我的首选方法如下:

function UserSchema (add) {
  var schema = new Schema({
    someField: String
  });

  if(add) {
    schema.add(add);
  }

  return schema;
}

var userSchema = UserSchema();
var adminSchema = UserSchema({
  anotherField: String
});

哪个恰好回答了您的第二个问题, 是的,您可以add()字段。因此,要修改Schema的某些属性,可以对上述函数进行修改以解决您的问题:

function UserSchema (add, nameAndPhoneIsRequired) {
  var schema = new Schema({
    //...
    firstname: {type: String, validate: firstnameValidator, required: nameAndPhoneIsRequired},
    lastname: {type: String, validate: lastnameValidator, required: nameAndPhoneIsRequired},
    phone: {type: String, validate: phoneValidator, required: nameAndPhoneIsRequired},
  });

  if(add) {
    schema.add(add);
  }

  return schema;
}
2020-07-07