Chris Chong
Chris Chong

Reputation: 371

Loading Baqend References

Is there a way to load a referenced object with having to strip out the class name?

So for example, in my app I frequently load data from referenced classes.

So I have a data object with a reference to this: /db/Shifts/73c81cc9-fa14-4fbe-9839-10c4121b3fc6

return db.Shifts.load('73c81cc9-fa14-4fbe-9839-10c4121b3fc6')

is what is needed to load the reference, so I have a lot of this going on:

var cleanID = obj.ShiftID.replace('/db/Shifts/','');
return db.Shifts.load(cleanID)

Is there a better way to do this? Like this?

return db.load('/db/Shifts/73c81cc9-fa14-4fbe-9839-10c4121b3fc6')

Upvotes: 0

Views: 53

Answers (1)

Florian Bücklers
Florian Bücklers

Reputation: 176

Yes, there are many ways how your problem can be solved.

You can load an object by id (/db/Shifts/73c81cc9-fa14-4fbe-9839- 10c4121b3fc6) or by a key (73c81cc9-fa14-4fbe-9839-10c4121b3fc6) both is supported by the load method.

// resolves both to the same object
db.Shifts.load('/db/Shifts/73c81cc9-fa14-4fbe-9839-10c4121b3fc6')
db.Shifts.load('73c81cc9-fa14-4fbe-9839-10c4121b3fc6')

You can access the id or the key directly from any object reference by using the corresponding accessors:

For instance, you have an object obj which have a reference shift to a Shifts instance. Then you can easily access the id or key of the reference directly.

obj.shift.id == '/db/Shifts/73c81cc9-fa14-4fbe-9839-10c4121b3fc6'
obj.shift.key == '73c81cc9-fa14-4fbe-9839-10c4121b3fc6'

If you want to load that reference you can use the reference load method directly:

obj.shift.load().then(shift => {
    shift.property = 'name';

    // Note that the obj.shift reference is resolved by the load call
    obj.shift === shift;

    return shift.save(); //do whatever you want to do with the reference
})

It is described in our guide in object references.

Another way to load the object with the referenced shift object directly is deep loading You can use deep loading to load an object with its references with one call:

// The depth: 1 parameter ensures that all directly referenced objects of obj
// will be resolved by the load call
DB.MyClassWithShiftReference.load(id, {depth: 1}).then(obj => {
    obj.shift.property = 'name';
})

Upvotes: 1

Related Questions