Mongoose Schema,如何在一个模式中嵌套对象?

时间:2016-05-27 03:45:04

标签: mongodb mongoose

在我的mongoose模式中,我定义了一些数据类型和两个对象数组。 第一个对象菜应该没问题。

但是在第二个嵌套对象顺序中,我想要包含第一个对象盘,我不知道如何正确地执行此操作。

module.exports = function( mongoose) {
      var ShopSchema = new mongoose.Schema({
        shopName:     { type: String, unique: true },
        address:     { type: String},
        location:{type:[Number],index: '2d'},
        shopPicUrl:      {type: String},
        shopPicTrueUrl:{type: String},
        mark:  { type: String},
        open:{type:Boolean},
        shopType:{type:String},

        dish:   {type: [{
          dishName: { type: String},
          tags: { type: Array},
          price: { type: Number},
          intro: { type: String},
          dishPic:{ type: String},
          index:{type:Number},
          comment:{type:[{
            date:{type: Date,default: Date.now},
            userId:{type: String},
            content:{type: String}
          }]}
        }]},

        order:{type:[{
          orderId:{type: String},
          date:{type: Date,default: Date.now},
          dish:{type: [dish]},//!!!!!!!!! could I do this?
          userId:{type: String}
        }]}

      });

1 个答案:

答案 0 :(得分:6)

这是设计模型的正确方法

var mongoose = require('mongoose');
Schema = mongoose.Schema;

var DishSchema = new mongoose.Schema({
  dishName: { type: String },
  tags:     { type: Array },
  price:    { type: Number },
  intro:    { type: String },
  dishPic:  { type: String },
  index:    { type: Number },
  comment:  { type: [{
    date:     {type: Date, default: Date.now },
    userId:   {type: String },
    content:  {type: String }
  }]}
});

var ShopSchema = new mongoose.Schema({
  shopName:       { type: String, unique: true },
  address:        { type: String },
  location:       { type: [Number], index: '2d' },
  shopPicUrl:     { type: String },
  shopPicTrueUrl: { type: String },
  mark:           { type: String },
  open:           { type: Boolean },
  shopType:       { type: String },
  dish:           { type: [DishSchema] },
  order:          { type: [{
    orderId:  { type: String },
    date:     { type: Date, default: Date.now },
    dish:     { type: [DishSchema] },
    userId:   { type: String }
  }]}
});

var Shop = mongoose.model('Shop', ShopSchema);
module.exports = Shop;