2013-10-27 260 views
0

我想抽象離我的貓鼬的架構模型:貓鼬單嵌套模式

AddressSchema = mongoose.Schema(
    _type: String 
    first_name: String 
    last_name: String 
    address_line1: String 
    address_line2: String 
    zip_code: String 
    city: String 
    state: String 
    phone_number: Number 
) 
AddressSchema = Schema.AddressSchema 

,然後做這樣的事情以後:

ShippingChoicesRequestSchema = mongoose.Schema(
    retailer: String 
    products: [ ProductSchema ] 
    shipping_address: 
    ref: AddressSchema 
    type: ObjectId 
) 

然而,當我發送的請求,它不會創建這個嵌套的地址文檔。我知道我可以通過做像shipping_address: [ AddressSchema]這樣的數組來做到這一點,但如果它不是重複的字段呢?

編輯:

請求看起來像:

{ 
    "retailer": "something", 
    "products": [...], 
    "shipping_address": { 
    "_type": "address", 
    "first_name": "...", 
    "last_name": "...", 
    "address_line1": "...", 
    "address_line2": "...", 
    "zip_code": "...", 
    "city": "...", 
    "state": "...", 
    "phone_number": ... 
    } 
} 

但是,當我看着它在我蒙戈得到:

{ 
    "retailer" : "something", 
    "_id" : ObjectId("526ad0a3c0cff58a54000001"), 
    "products" : [ 
    { 
     "variant_choice" : { 
     "unit_price" : 3999, 
     "color" : "Black", 
     "size" : "M", 
     "_type" : "variant_choice" 
     }, 
     "quantity" : 1, 
     "product_id" : "123456", 
     "_type" : "product" 
    } 
    ], 
    "__v" : 0 
} 

因此地址不會被保存。

+0

什麼你的請求看起來像嗎? –

回答

0

在這裏,我們所定義的架構:

AddressSchema = mongoose.Schema(
    _type: String 
    first_name: String 
    last_name: String 
    address_line1: String 
    address_line2: String 
    zip_code: String 
    city: String 
    state: String 
    phone_number: Number 
); 

您還需要定義模型:

var AddressModel = mongoose.model('Address', AddressSchema); 

然後,我們可以參考地址爲subdoc的:

ShippingChoicesRequestSchema = mongoose.Schema(
    retailer: String 
    products: [ ProductSchema ] 
    shipping_address: {type: ObjectId, ref: 'Address'} 
); 
+0

謝謝!現在我得到了一個不同的錯誤,但是:'{message:'在路徑「shipping_address」'處強制緩衝失敗以獲得值「[object Object]」,有沒有辦法讓我一次定義整個'ShippingChoiceRequest'沒有單獨定義嵌套地址? – maxko87