Мангуст заселён в Keystone.js - PullRequest
0 голосов
/ 06 декабря 2018

Я пытался использовать mongoose populate в keystone.js приложении.С тех пор возникли все виды неприятностей.Вот моя пользовательская модель

'use strict';

const keystone = require('keystone');
const Types = keystone.Field.Types;
let Country = keystone.list('Country');

/**
    * User Model
    * ==========
    */
let User = new keystone.List('User', {history: true});

User.add({
    name: {type: Types.Name, required: true, index: true},
    email: {type: Types.Email, initial: true, required: true, unique: true, index: true},
    password: {type: Types.Password, initial: true, required: false},
    phone: {type: Types.Text, unique: true},
    avatar: {type: Types.Text},
    registrationEnd: {type: Types.Date},
    registrationStart: {type: Types.Date},
    utitle: {type: Types.Relationship, ref: 'Title'},
    dob: {type: Types.Date, format: 'DD/MM/YYYY'},
    permAddress: {
        type: Types.Location,
        state: {type: Types.Relationship, ref: 'State'},
        country: {type: Types.Relationship, ref: 'Country'}
    },
    sor: {type: Types.Relationship, ref: 'State'},
    lga: {type: Types.Relationship, ref: 'LGA'},
    religion: {type: Types.Relationship, ref: 'Religion'},
    marital: {type: Types.Relationship, ref: 'Marital'},
    sex: {type: Types.Select, options: 'male, female'},
    education: {type: Types.Relationship, ref: 'Education', dependsOn: {isClient: true}},
    seenLawyer: {type: Boolean, default: false, dependsOn: {isClient: true}},
    occupation: {type: Types.Relationship, ref: 'Occupation', dependsOn: {isClient: true}},
    firm: {type: Types.Text, dependsOn: {isLawyer: true}},
    lawyerSince: {type: Types.Date, dependsOn: {isLawyer: true}},
    areas: {type: Types.Relationship, ref: 'LawArea', default: false, many: true, dependsOn: {isLawyer: true}},
}, 'Permissions', {
    isAdmin: {type: Boolean, label: 'Can access Keystone', index: true, default: false},
    isLawyer: {type: Boolean, index: true, default: false},
    isClient: {type: Boolean, index: true, default: false},
});
User.schema.pre('save', function (next) {
    let thisUser = this;
    Country.model.findOne({name: 'Denmark'}).then((result) => {
        thisUser.permAddress.country = result._id;
        next();
    });
});
User.schema.virtual('canAccessKeystone').get(function () {
    return this.isAdmin;
});
User.schema.virtual('law').get(function () {
    return this.isLawyer;
});
User.schema.virtual('client').get(function () {
    return this.isClient;
});
User.schema.virtual('fullname').get(function () {
    return this.name.first + ' ' + this.name.last;
});
// Return only a user's _id
User.statics = {
    getUserId: function (email, cb) {
        this.findOne({email: email}).select('_id').exec(cb);
    }
};
User.defaultColumns = 'name, email, isLawyer, isAdmin';
User.register();

Из этой модели utitle, sor, lga и несколько других путей являются отношениями, которые, согласно Keystone, должны ссылаться на действительный идентификатор объекта MongoDB.,Теперь я пытаюсь заполнить документ из этой модели при поиске.Вот фрагмент из функции экспорта маршрутизатора.

view.on('init', function (next) {
        console.log(req.user.email);
        keystone.list('User').model.findOne({email: req.user.email}).populate({
            path: 'utitle',
            select: 'name'
        }).populate({path: 'sor', select: 'name'}).populate({path: 'lga', select: 'name'}).populate({
            path: 'religion',
            select: 'name'
        }).populate({path: 'marital', select: 'name'}).populate({
            path: 'education',
            select: 'name'
        }).populate({path: 'occupation', select: 'name'}).exec(function (err, results) {

            if (err || !results.length) {
                return next(err);
            }

            console.log(results); // Expect to find populated documents
            locals.user = results; next(err);

        });
    });

    locals.clientType = 'Free';
    locals.profilelink = '/portal/profile';

    // Render the view
    if (link === undefined) {
        view.render('portal/client', {layout: 'portal'});
    } else {
        view.render('client/' + link, {layout: 'portal'});
    }

Вот результат моего console.log

{ name: { first: 'Mike', last: 'Mikey' },
  permAddress:
   { country: '5c08562d6ca7fa009b16d2ce',
     postcode: '220282',
     state: '5c08562d6ca7fa009b16d2d8',
     street1: '22, Ajanlekoko Street, ',
     suburb: 'Abule-Egba' },
  seenLawyer: false,
  areas: [],
  isAdmin: false,
  isLawyer: false,
  isClient: true,
  _id: 5c08562e6ca7fa009b16d310,
  email: 'xxxxxx@xxx.xx',
  password:
   'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  phone: '0703268xxxx',
  __rev: 3,
  __v: 0,
  avatar: '',
  dob: 2018-12-04T23:00:00.000Z,
  registrationEnd: 2018-12-04T23:00:00.000Z,
  registrationStart: 2018-12-04T23:00:00.000Z,
  utitle: 5c08562e6ca7fa009b16d2ee,
  education: 5c08562e6ca7fa009b16d2f9,
  lga: 5c08562d6ca7fa009b16d2db,
  marital: 5c08562e6ca7fa009b16d2e5,
  occupation: 5c08562e6ca7fa009b16d309,
  religion: 5c08562e6ca7fa009b16d2e0,
  sex: 'female',
  sor: 5c08562d6ca7fa009b16d2d8 }

, который аналогичен тому, когда я вообще не заполняюсь.Все указанные модели не повреждены, как видно из интерфейса администратора.

Прошу прощения за грубость вопроса и скажите, что я делаю неправильно.

...