Inder R Singh
Inder R Singh

Reputation: 652

creating many to many relationship with keystone on existing database

I want to add object reference in existing database. Right now i have both database(domains & LabConfigs) up & running & they both have there instances which i could see from robomongo.

LabConfigs look like this

         id_:12345 (objectId)
         labConfig: test1
         id_:67890 (objectId)
         labConfig: test2

DomainName look like this

         id_:8787897 (objectId)
         domainName:ggogle.com
         id_:34234234 (objectId)
         domainName:fb.com

Now when i start my keystone, with following schema.

****************LabConfigs***********************
var LabConfigs = new keystone.List('LabConfigs');

LabConfigs.add({
 configName: {type: Types.Text, required: true, initial: true, index: true}
});
 LabConfig.defaultColumns = 'configName';
 LabConfig.register();

************************************************

And this is my second database.

var Domain = new keystone.List('Domain');

Domain.add({
  domainName: {type: Types.Text, required: true, initial: true, index: true},
  labConfigs :{type: Types.Relationship, ref: 'LabConfigs',required: false,many: true},
   userauthlevel:{ type: Types.TextArray}
  });


Domain.defaultColumns = 'domainName';
Domain.register();

Now I want is to add labConfigs in domain database as an array. i.e. each labConfigs has a relationship to domain array.

In keystone

  1. Where to add in keystone starting i.e. to build this many to many relationship ?
  2. Which query should i do build this relationship in that ( init ) function ?

Answer 1 --> I searched too much & figure out that it is good idea to have it in

 view.on('init', function())}

Upvotes: 0

Views: 320

Answers (1)

Shea Hunter Belsky
Shea Hunter Belsky

Reputation: 3238

You have the labconfigs field on your Domain model, and you've set many: true on it. Now you can specify an array of LabConfig IDs on the Domain document. When you save a Domain, you can set labConfigs to be equal to an array of labConfig document IDs. You can also create an array of labConfigs themselves, instead of their IDs. Keystone will save the references to the objects in the same way.

view.on('post', function (next) {
    var labConfigIDs = []; // Array of labConfig IDs, created however you want
    domain.getUpdateHandler(req).process({
        labConfigs: labConfigIDs
    }, {
        flashErrors: true,
        errorMessage: 'There was a problem updating your domain.'
    }, function(err) {
        if (err) {
            req.flash("error", saveErr.message);
            return next();
        } else {
            req.flash('success', 'Your changes have been saved.');
            return next();
        }
    });
});

Upvotes: 1

Related Questions