I'm using mongodb and nested documents is a basic database feature.
However, as per loopback documentation on embedded relations, one can't create a nested schema "at once".
So, if I have multiple embedded models, like addresses, multiple emails/phone numbers, etc., it would mean that I would need to call the API as many times for a single create. I don't think this is the best approach as API calls to a remote server should be minimised to the extent possible, esp. on unreliable networks.
Is there any workaround for this at the moment - e.g. Custom remote methods?
Thanks much.
Warm regards,
Aarti
ParentModel.createChildren = function(parentId, children, callback){
Const ChildModel = ParentModel.app.models.ChildModel
children.forEach(child => child.parentId = parentId); // set the parent Id of the children
ChildModel.create(children, callback);
// not sure if you can create multiple children at the same time for an EmbedsMany
// if not, just loop through or use Async and return the result. Still only 1 API call.
}
ParentModel.remoteMethod('createChildren', {
accepts:[
{arg:'parentId', type:'string', required: true},
{arg:'children', type:'array', required: true},
],
http: {path:'/Parents/:parentId/create-children', verb: 'POST'},
returns: {type: 'object', root: true},
});
I'm a little confused as I experimented with posting a JSON record containing an embedsOne record, using the standard post API through the API explorer, and it seamlessly added it. I'm using loopback 3.x. Not sure if they have recently added this functionality in and not yet updated the documentation? Or am I missing something?
Thanks much!
Warm regards,
Aarti
parent={
id: 1,
label: 'my model',
_children:[
{child 1},
{child 2},
{child 3}
]
}
// Url
POST /ParentModel/{id}
// Data
{
_children:[
{child 3},
{child 4},
{child 5}
]
}