Two classes: Contact and PhoneNumber. Contact has [ Data Relation (1:N): PhoneNumber ]
I’m currently working on importing data over REST and unfortunately I have to make separate table based REST requests. Most of this is working okay, but I have an afterCreate event on the PhoneNumber so that it locates the already imported Contact based on an importId field then associates itself with that contact.
In the code below there are a couple of console.log statements, one before and one after pushing the created PhoneNumber onto the Contact. In the console I can clearly see the before and after results are as expected. However, the save never seems to work as the relationship is not persisted. I’ve also tried the 1 to 1 with the relationship on the PhoneNumber and still can not get it to save the relationships.
phonenumber/afterCreate.js
var Contact = require('../../../models/contact');
var PhoneNumber = require('../../../models/phonenumber');
Backendless.ServerCode.Persistence.afterCreate('PhoneNumber', function(req, res) {
var dataQuery = new Backendless.DataQuery();
dataQuery.condition = 'importId = ' + res.result.phoneableId;
var contactsStore = Backendless.Persistence.of( Contact );
contactsStore.find( dataQuery )
.then( results => {
contact = results.data[0]
if (contact) {
console.log(require('util').inspect(contact, { depth: null }));
contact.phoneNumbers.push(res.result);
console.log(require('util').inspect(contact, { depth: null }));
return contact.save();
//return contactsStore.save(contact)
}
}).catch(err => {
return Promise.reject('Got an error : ' + err.message)
});
});
contact.js
class Contact extends Backendless.ServerCode.PersistenceItem {
constructor() {
super();
/**
@name Contact#importId
@type Number
*/
this.importId = undefined;
/**
@name Contact#lastName
@type String
*/
this.lastName = undefined;
/**
@name Contact#phoneNumbers
@type Array.<PhoneNumber>
*/
this.phoneNumbers = undefined;
/**
@name Contact#firstName
@type String
*/
this.firstName = undefined;
}
}
module.exports = Backendless.ServerCode.addType(Contact);