用匹配元素更新子子文档的数组

时间:2019-01-28 17:07:26

标签: mongodb mongoose-schema

以下是我的架构:

{  
   "_id":ObjectId("5c49c783de72ec2ec47b95d1"),
   "placement":[  
      {  
         "offer":[  
            {  
               "sent_by":"John",
               "comment":""
            },
            {  
               "sent_by":"Mary",
               "comment":""
            }
         ]
      }
   ]
}

我想更新placement.offer.comment,其中placement.offer.sent_byMary,但它总是更新第一条记录。我不想提供像placement.0.offer.1.sent_by这样的硬编码数字。

这应该是生成的文档:

{  
   "_id":ObjectId("5c49c783de72ec2ec47b95d1"),
   "placement":[  
      {  
         "offer":[  
            {  
               "sent_by":"John",
               "comment":""
            },
            {  
               "sent_by":"Mary",
               "comment":"Some comment updated"
            }
         ]
      }
   ]
}

1 个答案:

答案 0 :(得分:0)

您需要使用array filters来实现:

require 'spec_helper'


describe ANY_S3_ACCESSOR_CLASS do

  before(:each) do
    @bucket = 'any_bucket'
    @key = 'any_key'
    @s3_double = Aws::S3::Client.new(stub_responses: true)
    Aws::S3::Client.stub(:new).with(anything).and_return(@s3_double)
  end

  context "getting an S3 document" do
    it "should get an S3 document successfully" do
      expected_get_output = 'any_output'
      @s3_double.stub(:get_object).with(anything).and_return(expected_get_output)
      returned_document = NY_S3_ACCESSOR.instance.get_document(@bucket, @key)

      expect(returned_document).to eq(expected_get_output)
    end
  end

  context "putting an S3 document" do
    it "should put a file saved locally to disk to S3 successfully" do
      expected_put_output = 'any_put_output'
      csv_file = CSV.open("#{Rails.root}/test/fixtures/any_well_formed_csv.csv")
      @s3_double.stub(:put_object).with(anything).and_return(expected_put_output)
      actual_put_output = NY_S3_ACCESSOR.instance.write_local_file(@bucket, @key, csv_file.path)

      expect(actual_put_output).to eq(expected_put_output)
    end
  end
end