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' }]

新しいドキュメントを作成するときは、最初に Address ドキュメントを作成して保存し、保存したドキュメントの ID を取得して にプッシュしlead.business_address_attributesます。

ID だけでなくアドレスを含むドキュメントを取得するには、mongoose のpopulate('business_address_attributes')メソッドを使用します。

于 2012-04-11T13:04:16.933 に答える