I'm using boot scripts to create some models and relations. For example I might have this:
+-------+ +----------+
| Order | --belongsTo--> | Customer |
+-------+ +----------+
and I'd like to create: 1 Customer
, and 1 Order
belonging to that Customer
.
I know that loopback-boot executes the scripts in server/boot
in filename alphabetical order, so I have the following boot scripts:
// 0-create-customer.js
module.exports = function(app) {
app.dataSources.mongoDs.autoupdate('Customer', function(err) {
if (err) throw err;
var obj = {name: 'Bob'};
app.models.Customer.findOrCreate({where: obj}, obj
, function(err, customer) {
if (err) throw err;
});
});
};
and for the Order
, I find the Customer
first and create the order with customer.id
:
// 1-create-order.js
module.exports = function(app) {
app.dataSources.mongoDs.autoupdate('Order', function(err) {
if (err) throw err;
app.models.Customer.findOne({where: {name: 'Bob'}}
, function(err, customer) {
if (err) throw err;
var obj = {customerId: customer.id, amount: 42};
app.models.Order.findOrCreate({where: obj}, obj
, function(err, order) {
if (err) throw err;
});
});
});
};
The problem is, it seems the boot scripts do not wait until the models are created before exiting, therefore sometimes I run into these errors in the second script:
TypeError: Cannot read property 'id' of null
referring to this line:
var obj = {customerId: customer.id, amount: 42};
^
I'd rather not add a small wait before creating the Order
since that seems flaky and won't guarantee the parent model's existence especially if the data source happens to be slow.
I'd also rather not have to combine all this code into a single file because my real project has lots of models and this will result in a huge unmaintainable file.
Is there a good way to wait for the parent model auto-migration to complete before starting on the child?