<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Merge duplicates code errors in APIs &amp; Integrations</title>
    <link>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1016004#M75286</link>
    <description>&lt;P&gt;Hi &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/192581"&gt;@CSteinbach&lt;/a&gt;&lt;/SPAN&gt; and welcome to the Community!&lt;BR /&gt;We are delighted to have you join us!&lt;BR /&gt;&lt;BR /&gt;Thank you for asking the Community and for sharing the code!&lt;BR /&gt;&lt;BR /&gt;Since this a public space, please make sure that there is no confidential information.&lt;BR /&gt;&lt;BR /&gt;I have found this similar thread where the solution from &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/600153"&gt;@GJakobTriad&lt;/a&gt;&lt;/SPAN&gt; on this post "&lt;A href="https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/882799" target="_blank"&gt;Custom code and Company deduplication&lt;/A&gt;" might help you.&lt;BR /&gt;&lt;BR /&gt;Also, I'd like to invite a couple of subject matter experts and Community Members to this conversation: Hi &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/551647"&gt;@andreaska&lt;/a&gt;&lt;/SPAN&gt;, &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/20405"&gt;@himanshurauthan&lt;/a&gt;&lt;/SPAN&gt; and &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/324811"&gt;@zach_threadint&lt;/a&gt;&lt;/SPAN&gt; do you have troubleshooting steps to help &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/192581"&gt;@CSteinbach&lt;/a&gt;&lt;/SPAN&gt;, please?&lt;BR /&gt;&lt;BR /&gt;Thank you very much and have a great day!&lt;BR /&gt;&lt;BR /&gt;Best,&lt;BR /&gt;Bérangère&lt;/P&gt;</description>
    <pubDate>Thu, 25 Jul 2024 08:28:53 GMT</pubDate>
    <dc:creator>BérangèreL</dc:creator>
    <dc:date>2024-07-25T08:28:53Z</dc:date>
    <item>
      <title>Merge duplicates code errors</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1015467#M75285</link>
      <description>&lt;P&gt;I was using the default merge duplicates code and updated the property that I need to merge contacts by which is "rim_no" (a unique customer identifyer in our database). I have set up the API key in "Secrets" but after a lot of trouble shooting, I just can't figure it out. Anyone have any ideas?&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Here's the code:&lt;/P&gt;&lt;LI-SPOILER&gt;&lt;P&gt;/**&lt;BR /&gt;* Searches for another contact with the same value of DEDUPE_PROPERTY.&lt;BR /&gt;* - If no matches are found, nothing happens&lt;BR /&gt;* - If one match is found, the enrolled contact is merged into the matching contact&lt;BR /&gt;* - If more than one match is found, the action fails&lt;BR /&gt;*/&lt;/P&gt;&lt;P&gt;const DEDUPE_PROPERTY = 'rim_no';&lt;/P&gt;&lt;P&gt;const hubspot = require('@hubspot/api-client');&lt;/P&gt;&lt;P&gt;exports.main = (event, callback) =&amp;gt; {&lt;BR /&gt;// Make sure to add your API key under "Secrets" above.&lt;BR /&gt;const hubspotClient = new hubspot.Client({&lt;BR /&gt;accessToken: process.env.SECRET_NAME,&lt;BR /&gt;});&lt;/P&gt;&lt;P&gt;hubspotClient.crm.contacts.basicApi&lt;BR /&gt;.getById(event.object.objectId, [DEDUPE_PROPERTY])&lt;BR /&gt;.then(contactResult =&amp;gt; {&lt;BR /&gt;let dedupePropValue = contactResult.body.properties[DEDUPE_PROPERTY];&lt;/P&gt;&lt;P&gt;// console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY} = ${dedupePropValue}`);&lt;BR /&gt;hubspotClient.crm.contacts.searchApi&lt;BR /&gt;.doSearch({&lt;BR /&gt;filterGroups: [{&lt;BR /&gt;filters: [{&lt;BR /&gt;propertyName: DEDUPE_PROPERTY,&lt;BR /&gt;operator: 'EQ',&lt;BR /&gt;value: dedupePropValue&lt;BR /&gt;}]&lt;BR /&gt;}]&lt;BR /&gt;})&lt;BR /&gt;.then(searchResults =&amp;gt; {&lt;BR /&gt;let idsToMerge = searchResults.body.results&lt;BR /&gt;.map(object =&amp;gt; object.id)&lt;BR /&gt;.filter(vid =&amp;gt; Number(vid) !== Number(event.object.objectId));&lt;/P&gt;&lt;P&gt;if (idsToMerge.length == 0) {&lt;BR /&gt;console.log('No matching contact, nothing to merge');&lt;BR /&gt;return;&lt;BR /&gt;} else if (idsToMerge.length &amp;gt; 1) {&lt;BR /&gt;console.log(`Found multiple potential contact IDs ${idsToMerge.join(', ')} to merge`);&lt;BR /&gt;throw new Error("Ambiguous merge; more than one matching contact");&lt;BR /&gt;}&lt;/P&gt;&lt;P&gt;let idToMerge = idsToMerge[0];&lt;BR /&gt;console.log(`Merging enrolled contact id=${event.object.objectId} into contact id=${idToMerge}`);&lt;BR /&gt;hubspotClient&lt;BR /&gt;.apiRequest({&lt;BR /&gt;method: 'PATCH',&lt;BR /&gt;path: `/crm/v3/objects/contacts/IDOFSECONDARY`,&lt;BR /&gt;body: {&lt;BR /&gt;"properties": {&lt;BR /&gt;"dupe": "duplicate"&lt;BR /&gt;}&lt;/P&gt;&lt;P&gt;}&lt;BR /&gt;})&lt;BR /&gt;.then(mergeResult =&amp;gt; {&lt;BR /&gt;console.log('Contacts merged!');&lt;BR /&gt;});&lt;BR /&gt;});&lt;BR /&gt;});&lt;BR /&gt;};&lt;/P&gt;&lt;/LI-SPOILER&gt;&lt;P&gt;Here's the error log:&amp;nbsp;&lt;/P&gt;&lt;LI-SPOILER&gt;&lt;PRE&gt;WARNING: The logs for this function have exceeded the 4KB limit.
...
ontrol-allow-credentials\":\"false\",\"cf-cache-status\":\"DYNAMIC\",\"cf-ray\":\"8a848b6a5f2887ac-IAD\",\"connection\":\"close\",\"content-length\":\"299\",\"content-type\":\"application/json;charset=utf-8\",\"date\":\"Wed, 24 Jul 2024 14:19:20 GMT\",\"nel\":\"{\\\"success_fraction\\\":0.01,\\\"report_to\\\":\\\"cf-nel\\\",\\\"max_age\\\":604800}\",\"report-to\":\"{\\\"endpoints\\\":[{\\\"url\\\":\\\"https:\\\\/\\\\/a.nel.cloudflare.com\\\\/report\\\\/v4?s=R2f5tgv4JVSRn%2FjWX2DmhksTGsVDCYh2KRLzkRPRHy6lR2%2BLNg0brV8fmXULq03p%2F9Sy8CyIfBqFoAT0dCrNOaRLH3%2FlYCa8AbHa5WufRcjIuF7wPZB%2FR3hfQN5raPot\\\"}],\\\"group\\\":\\\"cf-nel\\\",\\\"max_age\\\":604800}\",\"server\":\"cloudflare\",\"strict-transport-security\":\"max-age=31536000; includeSubDomains; preload\",\"vary\":\"origin, Accept-Encoding\",\"x-content-type-options\":\"nosniff\",\"x-envoy-upstream-service-time\":\"4\",\"x-evy-trace-listener\":\"listener_https\",\"x-evy-trace-route-configuration\":\"listener_https/all\",\"x-evy-trace-route-service-name\":\"envoyset-translator\",\"x-evy-trace-served-by-pod\":\"iad02/hubapi-td/envoy-proxy-7dd59b876-mtwxl\",\"x-evy-trace-virtual-host\":\"all\",\"x-hubspot-auth-failure\":\"401 Unauthorized\",\"x-hubspot-correlation-id\":\"5cb63b81-60bd-445e-93de-b503bbdacda5\",\"x-request-id\":\"5cb63b81-60bd-445e-93de-b503bbdacda5\"}","    at BasicApiResponseProcessor.&amp;lt;anonymous&amp;gt; (/opt/nodejs/node_modules/@hubspot/api-client/lib/codegen/crm/contacts/apis/BasicApi.js:227:23)","    at Generator.next (&amp;lt;anonymous&amp;gt;)","    at fulfilled (/opt/nodejs/node_modules/@hubspot/api-client/lib/codegen/crm/contacts/apis/BasicApi.js:5:58)","    at processTicksAndRejections (node:internal/process/task_queues:96:5)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: Error: HTTP-Code: 401","Message: An error occurred.","Body: {\"status\":\"error\",\"message\":\"Authentication credentials not found. This API supports OAuth 2.0 authentication and you can find more details at https://developers.hubspot.com/docs/methods/auth/oauth-overview\",\"correlationId\":\"5cb63b81-60bd-445e-93de-b503bbdacda5\",\"category\":\"INVALID_AUTHENTICATION\"}","Headers: {\"access-control-allow-credentials\":\"false\",\"cf-cache-status\":\"DYNAMIC\",\"cf-ray\":\"8a848b6a5f2887ac-IAD\",\"connection\":\"close\",\"content-length\":\"299\",\"content-type\":\"application/json;charset=utf-8\",\"date\":\"Wed, 24 Jul 2024 14:19:20 GMT\",\"nel\":\"{\\\"success_fraction\\\":0.01,\\\"report_to\\\":\\\"cf-nel\\\",\\\"max_age\\\":604800}\",\"report-to\":\"{\\\"endpoints\\\":[{\\\"url\\\":\\\"https:\\\\/\\\\/a.nel.cloudflare.com\\\\/report\\\\/v4?s=R2f5tgv4JVSRn%2FjWX2DmhksTGsVDCYh2KRLzkRPRHy6lR2%2BLNg0brV8fmXULq03p%2F9Sy8CyIfBqFoAT0dCrNOaRLH3%2FlYCa8AbHa5WufRcjIuF7wPZB%2FR3hfQN5raPot\\\"}],\\\"group\\\":\\\"cf-nel\\\",\\\"max_age\\\":604800}\",\"server\":\"cloudflare\",\"strict-transport-security\":\"max-age=31536000; includeSubDomains; preload\",\"vary\":\"origin, Accept-Encoding\",\"x-content-type-options\":\"nosniff\",\"x-envoy-upstream-service-time\":\"4\",\"x-evy-trace-listener\":\"listener_https\",\"x-evy-trace-route-configuration\":\"listener_https/all\",\"x-evy-trace-route-service-name\":\"envoyset-translator\",\"x-evy-trace-served-by-pod\":\"iad02/hubapi-td/envoy-proxy-7dd59b876-mtwxl\",\"x-evy-trace-virtual-host\":\"all\",\"x-hubspot-auth-failure\":\"401 Unauthorized\",\"x-hubspot-correlation-id\":\"5cb63b81-60bd-445e-93de-b503bbdacda5\",\"x-request-id\":\"5cb63b81-60bd-445e-93de-b503bbdacda5\"}","    at process.&amp;lt;anonymous&amp;gt; (file:///var/runtime/index.mjs:1276:17)","    at process.emit (node:events:513:28)","    at emit (node:internal/process/promises:140:20)","    at processPromiseRejections (node:internal/process/promises:274:27)","    at processTicksAndRejections (node:internal/process/task_queues:97:32)"]}
Unknown application error occurred
Runtime.Unknown

Memory: 75/128 MB
Runtime: 1163.15 ms&lt;/PRE&gt;&lt;/LI-SPOILER&gt;</description>
      <pubDate>Wed, 24 Jul 2024 14:25:30 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1015467#M75285</guid>
      <dc:creator>CSteinbach</dc:creator>
      <dc:date>2024-07-24T14:25:30Z</dc:date>
    </item>
    <item>
      <title>Re: Merge duplicates code errors</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1016004#M75286</link>
      <description>&lt;P&gt;Hi &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/192581"&gt;@CSteinbach&lt;/a&gt;&lt;/SPAN&gt; and welcome to the Community!&lt;BR /&gt;We are delighted to have you join us!&lt;BR /&gt;&lt;BR /&gt;Thank you for asking the Community and for sharing the code!&lt;BR /&gt;&lt;BR /&gt;Since this a public space, please make sure that there is no confidential information.&lt;BR /&gt;&lt;BR /&gt;I have found this similar thread where the solution from &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/600153"&gt;@GJakobTriad&lt;/a&gt;&lt;/SPAN&gt; on this post "&lt;A href="https://community.hubspot.com/t5/APIs-Integrations/Custom-code-and-Company-deduplication/m-p/882799" target="_blank"&gt;Custom code and Company deduplication&lt;/A&gt;" might help you.&lt;BR /&gt;&lt;BR /&gt;Also, I'd like to invite a couple of subject matter experts and Community Members to this conversation: Hi &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/551647"&gt;@andreaska&lt;/a&gt;&lt;/SPAN&gt;, &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/20405"&gt;@himanshurauthan&lt;/a&gt;&lt;/SPAN&gt; and &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/324811"&gt;@zach_threadint&lt;/a&gt;&lt;/SPAN&gt; do you have troubleshooting steps to help &lt;SPAN style="background: var(--ck-color-mention-background); color: var(--ck-color-mention-text);"&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/192581"&gt;@CSteinbach&lt;/a&gt;&lt;/SPAN&gt;, please?&lt;BR /&gt;&lt;BR /&gt;Thank you very much and have a great day!&lt;BR /&gt;&lt;BR /&gt;Best,&lt;BR /&gt;Bérangère&lt;/P&gt;</description>
      <pubDate>Thu, 25 Jul 2024 08:28:53 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1016004#M75286</guid>
      <dc:creator>BérangèreL</dc:creator>
      <dc:date>2024-07-25T08:28:53Z</dc:date>
    </item>
    <item>
      <title>Re: Merge duplicates code errors</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1016496#M75303</link>
      <description>&lt;P&gt;I have continued troubleshooting using the resources provided, but I'm still running into errors.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Here the updated code:&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;/**
 * Searches for another contact with the same value of DEDUPE_PROPERTY.
 * - If no matches are found, nothing happens
 * - If one match is found, the enrolled contact is merged into the matching contact
 * - If more than one match is found, the action fails
 */

const DEDUPE_PROPERTY = 'rim_no';

const hubspot = require('@hubspot/api-client');

exports.main = (event, callback) =&amp;gt; {
  // Make sure to add your API key under "Secrets" above.
  const hubspotClient = new hubspot.Client({
    accessToken: process.env.[INSERT ACCESS TOKEN]
  });

  hubspotClient.crm.contacts.basicApi
    .getById(event.object.objectId, [DEDUPE_PROPERTY])
    .then(contactResult =&amp;gt; {
      let dedupePropValue = contactResult.body.properties[DEDUPE_PROPERTY];

    console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY} = ${dedupePropValue}`);
      hubspotClient.crm.contacts.searchApi
        .doSearch({
          filterGroups: [{
            filters: [{
              propertyName: DEDUPE_PROPERTY,
              operator: 'EQ',
              value: dedupePropValue
            }]
          }]
        })
        .then(searchResults =&amp;gt; {
          let idsToMerge = searchResults.body.results
            .map(object =&amp;gt; object.id)
            .filter(vid =&amp;gt; Number(vid) !== Number(event.object.objectId));

          if (idsToMerge.length == 0) {
            console.log('No matching contact, nothing to merge');
            return;
          } else if (idsToMerge.length &amp;gt; 1) {
            console.log(`Found multiple potential contact IDs ${idsToMerge.join(', ')} to merge`);
            throw new Error("Ambiguous merge; more than one matching contact");
          }

          let idToMerge = idsToMerge[0];
          console.log(`Merging enrolled contact id=${event.object.objectId} into contact id=${idToMerge}`);
          hubspotClient
            .apiRequest({
              method: 'POST',
              path: `/contacts/v1/contact/merge-vids/${idToMerge}`,
              body: {
                vidToMerge: event.object.objectId
              }
            })
            .then(mergeResult =&amp;gt; {
              console.log('Contacts merged!');
            });
        });
    });
};&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Here's the new error:&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="markup"&gt;2024-07-25T19:04:33.715Z	ERROR	Unhandled Promise Rejection 	{"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"TypeError: Cannot read properties of undefined (reading 'properties')","reason":{"errorType":"TypeError","errorMessage":"Cannot read properties of undefined (reading 'properties')","stack":["TypeError: Cannot read properties of undefined (reading 'properties')","    at /var/task/file.js:21:48","    at processTicksAndRejections (node:internal/process/task_queues:96:5)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: TypeError: Cannot read properties of undefined (reading 'properties')","    at process.&amp;lt;anonymous&amp;gt; (file:///var/runtime/index.mjs:1276:17)","    at process.emit (node:events:513:28)","    at emit (node:internal/process/promises:140:20)","    at processPromiseRejections (node:internal/process/promises:274:27)","    at processTicksAndRejections (node:internal/process/task_queues:97:32)"]}
Unknown application error occurred
Runtime.Unknown

Memory: 75/128 MB
Runtime: 1438.88 ms&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 25 Jul 2024 19:07:12 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1016496#M75303</guid>
      <dc:creator>CSteinbach</dc:creator>
      <dc:date>2024-07-25T19:07:12Z</dc:date>
    </item>
    <item>
      <title>Re: Merge duplicates code errors</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1017361#M75341</link>
      <description>&lt;P&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/192581"&gt;@CSteinbach&lt;/a&gt;&amp;nbsp;were you able to resolve the code issue?&lt;/P&gt;
&lt;P&gt;We have created a plugin to make deduplication easy in HubSpot. Of the main feature is a &lt;A href="https://koalify.io/knowledge-base/how-to-automatically-merge-hubspot-duplicates-using-koalify-workflow-actions" target="_blank" rel="noopener"&gt;workflow action that merges contact/companies.&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;I thought this might be relevant!&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;span class="lia-inline-image-display-wrapper lia-image-align-inline" image-alt="Jonas_De_Mets_0-1722082019115.jpeg" style="width: 400px;"&gt;&lt;img src="https://community.hubspot.com/t5/image/serverpage/image-id/123348i1A17977F8C1C7EAC/image-size/medium?v=v2&amp;amp;px=400" role="button" title="Jonas_De_Mets_0-1722082019115.jpeg" alt="Jonas_De_Mets_0-1722082019115.jpeg" /&gt;&lt;/span&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Best regards,&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sat, 27 Jul 2024 12:09:04 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1017361#M75341</guid>
      <dc:creator>Jonas_De_Mets</dc:creator>
      <dc:date>2024-07-27T12:09:04Z</dc:date>
    </item>
    <item>
      <title>Re: Merge duplicates code errors</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1017871#M75354</link>
      <description>&lt;P&gt;Hi&amp;nbsp;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/192581"&gt;@CSteinbach&lt;/a&gt;&amp;nbsp;&lt;span class="lia-unicode-emoji" title=":waving_hand:"&gt;👋&lt;/span&gt;&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Looks like you've just referenced some keys that weren't present in the HubSpot API responses. Remove "body" from your "contactResult" and "searchResults" object chains. This has worked on my end, so please feel free to give it a try:&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;LI-CODE lang="javascript"&gt;/**
 * Searches for another contact with the same value of DEDUPE_PROPERTY.
 * - If no matches are found, nothing happens
 * - If one match is found, the enrolled contact is merged into the matching contact
 * - If more than one match is found, the action fails
 */

const DEDUPE_PROPERTY = 'rim_no';

const hubspot = require('@hubspot/api-client');

exports.main = (event, callback) =&amp;gt; {
  // Make sure to add your API key under "Secrets" above.
  const hubspotClient = new hubspot.Client({
    accessToken: process.env.[INSERT ACCESS TOKEN]
  });

  hubspotClient.crm.contacts.basicApi
    .getById(event.object.objectId, [DEDUPE_PROPERTY])
    .then(contactResult =&amp;gt; {
      let dedupePropValue = contactResult.properties[DEDUPE_PROPERTY];

    console.log(`Looking for duplicates based on ${DEDUPE_PROPERTY} = ${dedupePropValue}`);
      hubspotClient.crm.contacts.searchApi
        .doSearch({
          filterGroups: [{
            filters: [{
              propertyName: DEDUPE_PROPERTY,
              operator: 'EQ',
              value: dedupePropValue
            }]
          }]
        })
        .then(searchResults =&amp;gt; {
          let idsToMerge = searchResults.results
            .map(object =&amp;gt; object.id)
            .filter(vid =&amp;gt; Number(vid) !== Number(event.object.objectId));

          if (idsToMerge.length == 0) {
            console.log('No matching contact, nothing to merge');
            return;
          } else if (idsToMerge.length &amp;gt; 1) {
            console.log(`Found multiple potential contact IDs ${idsToMerge.join(', ')} to merge`);
            throw new Error("Ambiguous merge; more than one matching contact");
          }

          let idToMerge = idsToMerge[0];
          console.log(`Merging enrolled contact id=${event.object.objectId} into contact id=${idToMerge}`);
          hubspotClient
            .apiRequest({
              method: 'POST',
              path: `/contacts/v1/contact/merge-vids/${idToMerge}`,
              body: {
                vidToMerge: event.object.objectId
              }
            })
            .then(mergeResult =&amp;gt; {
              console.log('Contacts merged!');
            });
        });
    });
};&lt;/LI-CODE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Finally, if you're ever looking for an app to handle the merging of Contacts via workflows, you might like to consider &lt;A href="https://ecosystem.hubspot.com/marketplace/apps/productivity/workflow-automation/utilities-by-thread-integrations-2016879" target="_blank" rel="noopener"&gt;&lt;STRONG&gt;Utilities for HubSpot&lt;/STRONG&gt;&lt;/A&gt;.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;I hope this proves helpful. Please let me know if you have any follow-up questions &lt;span class="lia-unicode-emoji" title=":slightly_smiling_face:"&gt;🙂&lt;/span&gt;&lt;/P&gt;</description>
      <pubDate>Mon, 29 Jul 2024 06:08:04 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1017871#M75354</guid>
      <dc:creator>zach_threadint</dc:creator>
      <dc:date>2024-07-29T06:08:04Z</dc:date>
    </item>
    <item>
      <title>Re: Merge duplicates code errors</title>
      <link>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1018139#M75373</link>
      <description>&lt;P&gt;&lt;a href="https://community.hubspot.com/t5/user/viewprofilepage/user-id/324811"&gt;@zach_threadint&lt;/a&gt;&amp;nbsp;Thank you so much! I had tried to remove "body" but must have missed something! This works and I really really apprecate your help!!&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 29 Jul 2024 14:22:25 GMT</pubDate>
      <guid>https://community.hubspot.com/t5/APIs-Integrations/Merge-duplicates-code-errors/m-p/1018139#M75373</guid>
      <dc:creator>CSteinbach</dc:creator>
      <dc:date>2024-07-29T14:22:25Z</dc:date>
    </item>
  </channel>
</rss>

