将keystone.js插入关系字段

时间:2018-11-21 11:42:14

标签: javascript mongoose keystonejs

如果真是天真,我真的很抱歉,但是我已经花了太长时间了。 我的问题与this未回答的问题有关。我已经安装了Keystone 4,并且需要使用其update功能。这是一个国家模型:

'use strict';

const keystone = require('keystone');
const Types = keystone.Field.Types;
/**
 * Country Model
 * ============
 */

let Country = new keystone.List('Country', {
    autokey: { from: 'name', path: 'key', unique: true },
});
Country.add({
    name: { type: Types.Text, initial: true, required: true, unique: true },
    capital: { type: Types.Relationship, ref: 'State' },
});

// Get country's id
Country.schema.methods.getCountryId = function (name, cb) {
        this.model.findOne({ name: name }).select('_id').exec(cb);
    };

Country.register();

getCountryId()方法是这样,因此我可以在创建状态更新时在关系字段中提供ID,其模型如下所示:

'use strict'
;
const keystone = require('keystone');
const Types = keystone.Field.Types;
/**
 * State Model
 * ============
 */

let State = new keystone.List('State', {
    autokey: { from: 'name', path: 'key', unique: true },
});
State.add({
    name: { type: Types.Text, initial: true, required: true, unique: true },
    capital: { type: Types.Text },
    country: { type: Types.Relationship, initial: false, ref: 'Country', many: false, index: true }
});

// Return only a State's _id
State.statics = {
    getStateId: function (name, cb) {
        this.findOne({ name: name }).select('_id').exec(cb);
    }
};

State.register();

为简洁起见,现在状态更新:

'use strict';
const keystone = require('keystone');

let Country = keystone.list('Country');

// Get the _id of France
let france = Country.getCountryId('France', function (err, country) {
if (err) {
    // handle error, express example:
    console.err(err);
}

exports.create = {
    State: [
        { name: 'Nouvelle-Aquitaine', capital: 'Bordeaux', country: france },
        { name: 'Auvergne-Rhône-Alpes', capital: 'Lyon', country: france },
        ],
};

我当前的提交正在大量泄漏内存。但是在此之前,我一直在获取Country.getCountryId不是一个函数。我还尝试了Mongoose Populate的概念,它似乎仅在使用find*函数之一时才起作用。 显然我缺少了一些东西。请告诉我它是什么。

0 个答案:

没有答案