0

我想从我的 Mongoose 模式中抽象出一个模型:

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": ...
  }
}

但是当我在 Mongo 中查找时,我得到:

{
  "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
}

所以地址不会被存储。

4

1 回答 1

0

在这里,我们定义了 Schema:

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);

然后我们可以引用地址作为子文档:

ShippingChoicesRequestSchema = mongoose.Schema(
    retailer: String
    products: [ ProductSchema ]
    shipping_address: {type: ObjectId, ref: 'Address'}
);
于 2013-10-28T04:02:30.453 回答