How to replace relationship field type object IDs with names / titles in KeystoneJS list CSV download / export?

StackOverflow https://stackoverflow.com//questions/25057584

  •  21-12-2019
  •  | 
  •  

문제

In Keystone admin list view the handy download link exports all list items in a CSV file, however, if some of the fields are of Relationship type, the exported CSV contains Mongo ObjectIDs instead of nmeaningful strings (name, title, etc) which would be useful.

How can one force the ObjectIDs to be mapped / replaced by another field?

도움이 되었습니까?

해결책

Keystone has an undocumented feature that allows you to create your own custom CSV export function. This feature was added back in April (see KeystoneJS Issue #278).

All you need to do is add a method to the schema called toCSV. Keystone will inject any of the following dependencies when specified as arguments to this method.

 - req (current express request object)
 - user (currently authenticated user)
 - row (default row data, as generated without custom toCSV())
 - callback (invokes async mode, must be provided last)

You could, for example, use the Mongoose Model.Populate method to replace the Object Ids of any relationship field with whatever data you want.

Assume you have a Post list with an author field of Types.Relationship to another list (let's say User) which has a name field. You could replace the author Object Id with the author's name (from the User list) by doing the following.

Post.schema.methods.toCSV = function(callback) {

    var post = this,
        rtn = this.toJSON();

    this.populate('author', function() {
        rtn.author = post.author.name; // <-- author now has data from User list
        callback(null, rtn);
    });

};

.toCSV() will be called for every document returned with the Model as the context. When used asynchronously (as above) you should return a JSON representation of the new CSV data by passing it as the second argument of the callback. When using it synchronously simply return the updated JSON object.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top