Search code examples
realmrealm-mobile-platform

use function to set default value of a field inside schema


when i try to use function to set default value in realm schema

mCustomerId: {type: 'string', default: CreateGuid()}

i am getting following error

Customer.mCustomerId must be of type: string

let CustomerSchema ={

  name: 'Customer',
  primaryKey: 'mCustomerId',
  properties: {
    errorMessage:  {type: 'string', optional: true},
    status:{type: 'string', optional: true},
    address: {type: 'string', optional: true},
    customerNumber: {type: 'string', optional: true},
    city: {type: 'string', optional: true},
    contactId: {type: 'double', optional: true},
    country: {type: 'string', optional: true},
    customerId:{type: 'double', optional: true},
    customerRecordType: {type: 'string', optional: true},
    currency: {type: 'string', optional: true},
    email: {type: 'string', optional: true},
    custGroup: {type: 'string', optional: true},
    invoiceAndDeliveryOnHold: {type: 'string', optional: true},
    estimate: {type: 'string', optional: true},
    fax: {type: 'string', optional: true},
    firstName:{type: 'string', optional: true},
    lastName: {type: 'string', optional: true}, 
    mCustomerId: {type: 'string', default: CreateGuid()},   
    notes: {type: 'string', optional: true},    
    organizationName: {type: 'string', optional: true},
    phoneNumber: {type: 'string', optional: true},
    department: {type: 'string', optional: true},
    parentCompanyId: {type: 'double', optional: true},
    parentCompanyName: {type: 'string', optional: true},
    state: {type: 'string', optional: true},
    totalInvoiced: {type: 'double', optional: true},    
    zipcode: {type: 'string', optional: true},
    customerStatus: {type: 'string', optional: true},
    siteId: {type: 'string', optional: true},
    wareHouseId:{type: 'string', optional: true}
  }
};

i am fetching data from server where in mCustomerId will be null so we want to generate guid at our end and insert it into realm (its a business logic and we can not make customerId as primary key so request not to suggest this option)

function CreateGuid() {  

        function _p8(s) {  
          var p = (Math.random().toString(16)+"000000000").substr(2,8);  
          return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p ;  
        }  
        return _p8() + _p8(true) + _p8(true) + _p8();  
    } 

so how shall i achieving setting custom guid in realm javascript


Solution

  • You cannot specify a function to be called as the default value. I can definitely see the use case for it. Feel free to open an issue at https://github.com/realm/realm-js.