Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Schema, how to nest objects in one schema?

In my mongoose schema, I have defined some data types and two object array. The first object dish which should be ok.

But in the second nested object order I want to include the first object dish into and I do not know the way to do this properly.

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}
        }]}

      });
like image 899
Yan Li Avatar asked May 27 '16 03:05

Yan Li


1 Answers

this is correct way to design model

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;
like image 86
karthi Avatar answered Nov 11 '22 09:11

karthi