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

7
在我的mongoose模式中,我定义了一些数据类型和两个对象数组。第一个对象dish应该没问题。
但在第二个嵌套的对象order中,我想将第一个对象dish包含到其中,但我不知道正确的方法。
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个回答

23

这是设计模型的正确方式。

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;

我执行了这个操作并将数据推入数据库,但为什么我的DishSchema没有_id? - Yan Li
子文档 _id 将会生成。请检查一下。 - karthi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接