如何在猫鼬中创建嵌套的mongoDb模式?

时间:2019-05-15 08:13:41

标签: mongodb mongoose mongoose-schema

我正在尝试为用户和清洁用户设计猫鼬shema,他们有一些共同的领域,例如名称,但还有额外的(不同的字段)客户(等级)和客户编号。我不确定我的设计是否良好。

我为客户和清洁工创建了单独的userSchema,并创建了单独的地址模式。

// User Schema
const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
});

 // AddressSchema
 const AddressSchema = new mongoose.Schema({
   city: {
    type: String,
    required: true
   },
  street: {
    type: String,
    required: true
  }
});

// CustomerSchema
 const CustomerSchema= new mongoose.Schema({
  name: UserSchema,
  address: AddressSchema 
 });

// CleanerSchema
const CleanerSchema= new mongoose.Schema({
 name: UserSchema,
 rating: {
  type: Number,
  required: true
 }

});

我的模式不起作用。您能为我的模式提供最佳实践示例吗?

1 个答案:

答案 0 :(得分:0)

这就是定义客户和清洁器模式的方式。我认为没有必要创建单独的名称和地址架构。

const CustomerSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  address: {
    city: {
      type: String,
      required: true
    },
    street: {
      type: String,
      required: true
    }
  }
});

const CleanerSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  rating: {
    type: Number,
    required: true
  }
});