【问题标题】:Mongoose single nested modelMongoose 单嵌套模型
【发布时间】:2013-11-06 15:30:57
【问题描述】:

我想从我的 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
}

所以地址不会被存储。

【问题讨论】:

  • 您的请求是什么样的?

标签: node.js mongodb mongoose schema


【解决方案1】:

我们在这里定义 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'}
);

【讨论】:

  • 谢谢!现在我得到了一个不同的错误:{ message: 'Cast to buffer failed for value "[object Object]" at path "shipping_address"',有没有办法让我一次定义整个ShippingChoiceRequest,而不单独定义嵌套地址?
猜你喜欢
  • 2017-07-06
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2015-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
相关资源
最近更新 更多