Search code examples
javascriptmongodbrelationshipkeystonejs

How to get relationship model in Keystone.js


So I try to get 'Pronouns' model from 'Sentence' model from 'TestGenerator' model. And I have id's, but no model.

TestGenerator Model

var TestGenerator = new keystone.List('TestGenerator', {
    map: { name: 'title' },
    autokey: { path: 'slug', from: 'title', unique: true }
});

TestGenerator.add({
    title: { type: String, required: true },
    sentences: { type: Types.Relationship, ref: 'Sentence', many: true },
});

TestGenerator.register();

var Sentence = new keystone.List('Sentence', {
    map: { name: 'title' },
    autokey: { path: 'slug', from: 'title', unique: true }
});

Sentence Model

Sentence.add({
    title: { type: String, required: true },
    pronouns: { type: Types.Relationship, ref: 'Pronoun', many: true },
    verbs: { type: Types.Relationship, ref: 'Verb', many: true },
});

Sentence.relationship({ ref: 'TestGenerator', path: 'sentences' });

Sentence.register();

Ponoun model

var Pronoun = new keystone.List('Pronoun', {
    map: { name: 'english' },
    autokey: { path: 'slug', from: 'english', unique: true }, 
});

Pronoun.add({
    english: { type: String },
    russian: { type: String }
});

Pronoun.relationship({ ref: 'Sentence', path: 'pronouns' });

Pronoun.register();

And my controller

view.on('init', function (next) {

    var q = keystone.list('TestGenerator').model.findOne({
        slug: locals.filters.test_genetation,
    }).populate('sentences');

    q.exec(function (err, result) {
        locals.testGenerator = result;
        locals.current_sentence = result.sentences[0];
        locals.data.englishSentence = locals.current_sentence.pronouns;
        console.log(locals.data.englishSentence);
        next(err);
    });
});

And "locals.data.englishSentence" return

["5739bd696ef7d78d16e9e0e5","573ac7645e3d7d7210f1c4be"]

So how I can fix it? Don't understand.


Solution

  • This is related to mongoose, not Keystone actually. Mongoose doesn't provide deep population, you'll need a separate plugin like e.g. mongoose-deep-populate