0

我创建了一个表单,其中包含某些字段。我还有一个包含字段数组的字段。该字段的“req.body.lead”输出如下:

// output of console.log("req.body.lead",req.body.lead);
     business_address_attributes: 
      { address_type: 'Business',
        street1: 'Street 1...',
        street2: 'Street 2...',
        city: 'City...',
        state: 'State...',
        zipcode: 'Zip Code...',
        country: '' },

我可以将整个对象存储在另一个对象中:

      var address = new Addresses(req.body.lead.business_address_attributes);

在 mongodb 中,我已将一个字段声明为:

   business_address_attributes : [Addresses],
   //Note: [Addresses] refers to address class

现在,当我尝试使用以下方法存储内部 monogdb 时,出现错误,无法保存线索

var lead = new Leads(req.body.lead);
var address = new Addresses(req.body.lead.business_address_attributes);
lead.business_address_attributes.$push(address);
lead.save();
// console.log(lead.business_address_attributes) now gives following output:
    [ { address_type: 'Business',
  street1: 'Street 1...',
  street2: 'Street 2...',
  city: 'City...',
  state: 'State...',
  zipcode: 'Zip Code...',
  country: '',
  _id: 4f857a2e491383dc64000008 } ]

我不知道如何解决这个问题。有人可以帮忙。

4

1 回答 1

0

我对这个问题的解决方案是将包含文档数组的字段声明为参考数组。

Address为文档创建架构:

  var AddressSchema = new Schema({
     //attributes
  });

并创建一个模型:

mongoose.model('address', AddressSchema)

现在在父文档中你可以说

business_address_attributes : [{ type: Schema.ObjectId, ref: 'address' }]

创建新文档时,先创建地址文档,保存,获取已保存文档的 ID 并推送到lead.business_address_attributes.

要取回包含地址而不仅仅是 ID 的文档,请使用 mongoose 的populate('business_address_attributes')方法。

于 2012-04-11T13:04:16.933 回答