如何在mongodb中保存对象

时间:2012-04-11 12:38:23

标签: node.js mongodb express mongoose

我创建了一个表单,其中我有某些字段。我还有一个字段,其中包含一个字段数组。“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 } ]

我不知道如何解决问题。可以帮助。

1 个答案:

答案 0 :(得分: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')方法。