Ernie
Ernie

Reputation: 1000

Strongloop loopback: How can I add related model instances on a model instance in a boot script

I'm working on an API for a school platform. I want to migrate and seed the database in a boot script, while I'm still developing.

I can make school instances, group instances, and person instances, but I cannot figure out how to add a relation between the person instances and the group instances (Many to Many)

This is my Person .json file:

{
  "name": "Person",
  "base": "User",
  "strict": true,
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string",
      "required": true
    },
    "firstName": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "groups": {
      "type": "hasAndBelongsToMany",
      "model": "Group"
    },
    "school": {
      "type": "belongsTo",
      "model": "School"
    }
  },
  "acls": [],
  "methods": []
}

This is my group.json file

{
  "name": "Group",
  "base": "PersistedModel",
  "strict": true,
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "people": {
      "type": "hasAndBelongsToMany",
      "model": "Person"
    },
    "school": {
      "type": "belongsTo",
      "model": "School"
    }
  },
  "acls": [],
  "methods": []
}

And this is my boot script:

var async = require('async');

module.exports = function(app) {
    var mysqlDs = app.dataSources.mysqlDs;
    var boysNames = ["Lucas", "Liam", "Arthur", "Vince", "Noah", "Finn", "Mathis", "Louis", "Adam", "Jules", "Lars", "Seppe", "Stan", "Alexander", "Leon", "Kobe", "Victor", "Matteo", "Milan", "Mats", "Vic", "Wout", "Daan", "Senne", "Ferre", "Tuur", "Nathan", "Elias", "Warre", "Jack", "Felix", "Cas", "Thomas", "Lowie", "Robbe", "Lewis", "Rayan", "Nand", "Sem", "Maxim", "Emiel", "Jasper", "Oscar", "Mauro", "Sam", "Mohamed", "Luca", "Bent", "Ruben", "Simon", "Imran", "Jayden", "Lou", "Viktor", "Bas", "Lenn", "Rune", "Lukas", "Eden", "Emile"];
    var girlsNames = ["Emma", "Louise", "Elise", "Ella", "Marie", "Noor", "Lena", "Julie", "Lotte", "Olivia", "Anna", "Elena", "Mila", "Lore", "Fien", "Nina", "Lina", "Nora", "Laura", "Juliette", "Charlotte", "Lisa", "Amber", "Amélie", "Fleur", "Renée", "Lily", "Sara", "Camille", "Hanne", "Luna", "Liv", "Roos", "Helena", "Sarah", "Sofia", "Janne", "Noa", "Jade", "Nore", "Fenna", "Axelle", "Kato", "Alice", "Aya", "Jana", "Lize", "Paulien", "Amelie", "Lucie", "Lara", "Zoë", "Mona", "Manon", "Leonie", "Ines", "Oona", "Laure", "Mira", "Febe"];
    var names = ["Jong","Jansen","Vries","Visser","Jans","Bakker","Dijk","Vos","Smit","Berg","Boer","Groot","Janssen","Jacobs","Veen","Bos","Bergman","Hendriks","Dekker","Mulder","Willems","Meijer","Graaf","Leeuwen","Vermeulen","Koster","Peeters","Brouwer","Kok","Peters","Smits","Linden","Vliet","Wit","Beekman","Bosch","Meer","Koning","Beek","Haan","Vermeer","Verhoeven","Bruijn","Jonge","Heuvel","Martens","Dam","Hoek","Pieters","Walle","Bruin","Timmermans","Prins","Wouters","Janssens","Blom","Velde","Loon","Lange","Maas","Mol","Dijkstra","Post","Wal","Maes","Dieleman","Hermans","Jager","Stam","Gerrits","Groen","Roos","Wijk","Kuiper","Broek","Leeuw","Lambert","Kroon","Verdonck","Geerts","Boon","Hoekstra","Schouten","Gastel","Brink","Goossens","Steen","Bleijenberg","Bijl","Dubois","Jonker","Rooij","Driel","Pol","Ruiter","Stevens","Horst","Verbeek","Mertens","Ende","Sanders","Driessen","Huisman","Kooij","Schipper","Waal","Laan","Scholten","Vink","Ven","Postma","Aerts","Santen","Roovers","Verhulst","Verschoor","Ham","Moerman","Rijn","Bax","Franken","Eijk","Martin","Bosman","Meulen","Veenstra","Mostert","Velden","Harms","Wolters","Zanten","Claes","Poot","Ridder","Ginkel","Doorn","Heijden","Oost","Os","Blok","Kramer","Simons","Kuipers","Rovers","Cornelis","Dupont","Valk","Zwart","Gerard","Verweij"]

    //first lets recreate all databases
    mysqlDs.automigrate(function(){
        console.log("tables recreated: let's seed");

        async.parallel({
            schools: async.apply(createSchools)
            // ....
        }, function(errFase1, resultsFase1) {
            if (errFase1) throw errFase1;

            async.parallel({
                groups: async.apply(createGroups, resultsFase1.schools),
                persons: async.apply(createStudents, resultsFase1.schools),
            }, function(errFase2, resultsFase2) {
                if (errFase2) throw errFase2;

                // ???????????????????????????????????

                // ??? HOW TO add a relation between the persons and the groups
                // a person must be able to live 
                // in multiple groups

            });
        });
    });

    function createSchools(cb) {
        var School = app.models.School;
        School.create([
            {
                "name": "Harvard",
                "address": "xxx",
                "zip": "0000",
                "place": "yyy"  
            },
            {
                "name": "Oxford",
                "address": "xxx",
                "zip": "0000",
                "place": "yyy"  
            }
        ], cb);
    }



    function createGroups(schools,cb) {
        var Group = app.models.Group;
        Group.create([
            { "name": "Class 1", "schoolId": schools[0].id },
            { "name": "Class 2", "schoolId": schools[0].id },
            { "name": "Class 3", "schoolId": schools[0].id },
            { "name": "Class 4", "schoolId": schools[0].id },
            { "name": "Class 5", "schoolId": schools[0].id },
            { "name": "Class 6", "schoolId": schools[0].id },
            { "name": "Class 1", "schoolId": schools[1].id },
            { "name": "Class 2", "schoolId": schools[1].id },
            { "name": "Class 3", "schoolId": schools[1].id },
            { "name": "Class 4", "schoolId": schools[1].id },
            { "name": "Class 5", "schoolId": schools[1].id },
            { "name": "Class 6", "schoolId": schools[1].id },
        ], cb);
    }

    function createStudents(schools,cb) {
        var Person = app.models.Person;
        var students = [];
        for (var i = 0; i < 240; i++) {
            chooseFrom = (i%2 == 1) ? girlsNames : boysNames ;
            students.push({
                "name": names[i%names.length],
                "firstName": chooseFrom[i%chooseFrom.length],
                "username": "student"+i,
                "password": "testje",
                "email": "student"+i+"@mailinator.com",
                "emailVerified": true,
                "schoolId": schools[Math.floor(i/120)].id
            });
        };
        Person.create(students, cb);
    }
};

To add students to groups, I expected something like this, would do the trick :

Group.findOne(function(err, group){
    console.log(group);
    group.people().add(students[0].id);
})

I can't find any tutorials on this specific question.

I debugged the bootscript, and inspected the group variable, it's a ModelConstructor. I'm guessing I can get the related people via the people() function, but how can I add a person to a specific group?

Upvotes: 5

Views: 2744

Answers (2)

princecharmx
princecharmx

Reputation: 181

// id needs to be passed not entire instance. even loopbackjs docs needs to be updated

var student = students[0];
Group.findOne(function(err, group){
console.log(group);
group.people.add(student.id); // <--- id and not instance
})

Upvotes: 1

Related Questions