2017-07-31 142 views
0

我有問題,在貓鼬的相關模式: 我有3層架構:更改貓鼬架構視圖模型

var recipeProductSchema = new mongoose.Schema({ 
    product: { type: mongoose.Schema.Types.ObjectId, ref: 'Product' }, 
    productWeight: Number 
}, {toJSON: {virtuals: true}}); 

var recipeSchema = new mongoose.Schema({ 
    name: String, 
    products: [RecipeProduct] 
}) 

var productSchema = new mongoose.Schema({ 
    name: { 
     type: String, 
     required: true 
    }, 
    weight: { 
     type: Number, 
     required: true 
    }, 
    price: { 
     type: Number, 
     required: true 
    } 
}) 

當我想創建一個產品配方我送:

{ 
    "name": "Cake", 
    "products": [ 
     { 
      "product": "597a517b7c2e8508c8cc3f3a", 
      "productWeight": 50 
     } 
    ] 
} 

但是,當我得到關於食譜的詳細信息我得到這個:

{ 
    "_id": "597f7d0ce25d1413149aa30d", 
    "name": "Cake", 
    "products": [ 
     { 
      "product": { 
       "_id": "597a517b7c2e8508c8cc3f3a", 
       "name": "Sugar", 
       "weight": 400, 
       "price": 40 
      }, 
      "productWeight": 50, 
      "_id": "597b825a61736b1adcb0ed0f", 
      "productPrice": "5.00", 
      "id": "597b825a61736b1adcb0ed0f" 
     } 
    ] 
} 

是否有可能使這兩個json相似嗎? 因爲在編輯配方視圖中,我不想在數據發送之前更改配方的產品對象;

我想給這個JSON:

{ 
    "name": "Cake", 
    "products": [ 
     { 
      "product": { 
       "id": "597a517b7c2e8508c8cc3f3a" // or "_id" 
      }, 
      "productWeight": 50 
     } 
    ] 
} 

而且我想獲得:

{ 
    "_id": "597f7d0ce25d1413149aa30d", 
    "name": "Cake", 
    "products": [ 
     { 
      "product": { 
       "_id": "597a517b7c2e8508c8cc3f3a", 
       "name": "Sugar", 
       "weight": 400, 
       "price": 40 
      }, 
      "productWeight": 50, 
      "_id": "597f7d0ce25d1413149aa30e", 
      "productPrice": "5.00", 
      "id": "597f7d0ce25d1413149aa30e" 
     } 
    ] 
} 

回答

0

嘗試做一個兒童/父母關係

var recipeProductSchema = new mongoose.Schema({ 
    product: [productSchema], 
    productWeight: Number 
}, {toJSON: {virtuals: true}}); 

var recipeSchema = new mongoose.Schema({ 
    name: String, 
    products: [recipeProductSchema] 
}) 

var productSchema = new mongoose.Schema({ 
    name: { 
     type: String, 
     required: true 
    }, 
    weight: { 
     type: Number, 
     required: true 
    }, 
    price: { 
     type: Number, 
     required: true 
    } 
}) 

,並做了$push進入您的創建功能。

您還可以在您的獲取功能中使用貓鼬填充