在mongoose模式中添加对多个子文档的支持?

时间:2014-02-13 19:32:46

标签: javascript node.js mongodb mongoose database

我刚刚开始使用mongoose,我为我的数据声明了一个模式。我想知道如何将更多的子文档声明为相同的类型。假设我想添加第二个或第三个位置子文档,我该怎么做?

var nest_schema = mongoose.Schema({
company_name: String,
website: String,
chain: Boolean,
date: {
    date_added: Date,
    date_lastupdated: { type: Date, default: Date.now},     
    },
rating: {
    yelp_rating: Number,
    yelp_reviews: Number,
    user_rating: Number,
    },
locations: {
    location_number: Number,
    location_name: String,
    address: String,
    phone: String, 
    hours: {
        Monday: String,
        Tuesday: String,
        Wednesday: String,
        Thursday: String,
        Friday: String,
        Saturday: String,
        Sunday: String,
        },
drinks: {
    drink: String,
        sizes: {
            small: Number,
            medium: Number,
            large: Number,
            }
        }
        }
});

1 个答案:

答案 0 :(得分:1)

定义另一个架构并将其嵌入主架构中:

var nest_schema = mongoose.Schema({
  company_name: String,
  website: String,
  chain: Boolean,
  date: {
    date_added: Date,
    date_lastupdated: { type: Date, default: Date.now},     
  },
  rating: {
    yelp_rating: Number,
    yelp_reviews: Number,
    user_rating: Number,
  },
  locations: [locationSchema],
  drinks: [drinkSchema]
});

var locationSchema = mongoose.Schema({
  number: Number,
  name: String,
  address: String,
  phone: String, 
  hours: {
    Monday: String,
    Tuesday: String,
    Wednesday: String,
    Thursday: String,
    Friday: String,
    Saturday: String,
    Sunday: String,
  }
});

你可能也想让饮料成为自己的架构:

var drinksSchema = mongoose.Schema({ 
  drinks: {
    drink: String,
    sizes: {
      small: Number,
      medium: Number,
      large: Number,
    }
  }
});