[SalesForce] Inserting a record with a Master-Detail type field into a custom object using JSforce

How can a record with Master-Detail type field be inserted into a Salesforce object using JSforce package in Node.js

I have an object Email which is a child object of Person. Email contains a link to Person via a Master-Detail field named Person which links it back to the Person object.

I am inserting it in the following manner

conn.sobject('Email').create(
 {Name: 'name-for-record', 
  Email: 'user@domain.com', 
  Person: 'name-of-person-record'
 }, function(err, ret) {
  if (err || !ret.success) { return console.error(err, ret); }
  console.log("Created record id : " + ret.id);
});

This code gives the following error:

MALFORMED_ID: Person: id value of incorrect type

I understand that Person field has to be cast as Master-Detail type. However I cannot find a method to do so with the Jsforce package.

Best Answer

Your logic should be:

  1. Query the Salesforce Id of Parent (Person__c is its a custom object) record from DataBase using SOQL.

    • Create using create operation if it does not exists, you would get Salesforce Id back.
  2. Create Child (Email__c if its a custom object) record passing the lookup Id from above step.


Tried to add a psuedo code based on your requirement:

var records = [];
var accountRecordId = '';

// query the Account matching the name
conn.query("SELECT Id, Name FROM Account WHERE Name = 'Test Account' LIMIT 1", 
function(err, result) {
    if (err) { 
        return console.error(err); 
    }
    console.log("total : " + result.totalSize);
    console.log("fetched : " + result.records.length);

    if(result.records.length > 0) {
        accountRecordId = result.records[0].Id;
    }
});

if(accountRecordId == null) {
    // Create Account if it does not exists
    conn.sobject("Account").create({ 
        Name : 'Test Account' 
    }, function(err, ret) {
        if (err || !ret.success) { 
            // handle exception
            return console.error(err, ret); 
        }
        accountRecordId =  ret.id;
    });
}

// at this point we have accountRecordId populated


// Create child contact, use the Salesforce Account Id as a key for AccountId field
conn.sobject("Contact").create({ 
    LastName: 'Contact Name',
    AccountId: accountRecordId 
}, function(err, ret) {
    if (err || !ret.success) { 
        // handle exception
        return console.error(err, ret); 
    }
    console.log("Created record id : " + ret.id);
    // ...
});
Related Topic