有没有人有一个很好的例子,可以在keystonejs中为关系字段添加名称?现在它只保存一个id,所以如果我需要在玉器模板中显示那些字段名称,我还需要查询该关系模型。理想情况下是这样的:
var keystone = require('keystone'),
Types = keystone.Field.Types;
/**
* Titles Model
* =============
*/
var Title = new keystone.List('Title');
Title.add({
name: { type: String, required: true, initial: true },
room: { type: Types.Relationship, initial: true, required: true, ref: 'Screening', addNew: false },
businessUnit: { type: Types.Relationship, initial: true, required: true, ref: 'BusinessUnit', addNew: false }
});
Title.defaultSort = '-createdAt';
Title.defaultColumns = 'name, room';
Title.register();
会像这样保存:
title = {
name: 'name',
room: 3141234123442,
businessUnit: {
name: 'business name',
_id: 123412341234
}
}
如果没有例子,如果有人能够通过最佳实践来指导我做一个自定义关系字段类型来存储关系选择菜单中的值和id,我可能会想出来。该网站每个馆藏将有1000个文件,因此我现在需要关注绩效和最佳实践。
答案 0 :(得分:3)
你无法使用Keystone进行保存,但你可以将它设置为将对象按照你想要的方式传递给你的玉石模板。
您只需按照mongoose / mongodb功能“填充”关系字段。
**所以你的businessUnit模型可能如下所示:
var keystone = require('keystone');
var Types = keystone.Field.Types;
var BusinessUnit = new keystone.List('BusinessUnit', {
autokey: { from: 'name', path: 'key', unique: true },
plural: 'BusinessUnits'
});
BusinessUnit.add({
name: { type: String, required: true },
});
BusinessUnit.relationship({ ref: 'Title', path: 'title', refPath: 'businessUnit' });
BusinessUnit.register();
您的标题模型如上
var keystone = require('keystone'),
Types = keystone.Field.Types;
var Title = new keystone.List('Title');
Title.add({
name: { type: String, required: true, initial: true },
room: { type: Types.Relationship, initial: true, required: true, ref: 'Screening', addNew: false },
businessUnit: { type: Types.Relationship, initial: true, required: true, ref: 'BusinessUnit', addNew: false }
});
Title.defaultSort = '-createdAt';
Title.defaultColumns = 'name, room';
Title.register();
控制器的重要部分可能如下所示
//Get all Titles with their nested businessUnits.
view.on('init', function(next) {
keystone.list('Title').model.find()
.populate('businessUnit')
.exec(function(err, results) {
if(err) {
console.log(err);
return next(err);
} else {
locals.data.titlesWithNestedBusinessUnits = results;
next(err);
}
});
});
作为旁注,根据 .populate 方法功能,这只会一层深度。如果你想要深入(非常低效),你可以使用 mongoose deep populate 。 https://github.com/buunguyen/mongoose-deep-populate