Skip to content

Instantly share code, notes, and snippets.

@JedWatson
Last active September 17, 2019 02:41
Show Gist options
  • Save JedWatson/10739959 to your computer and use it in GitHub Desktop.
Save JedWatson/10739959 to your computer and use it in GitHub Desktop.
Examples of how to use Keystone's createItems functionality

Populating Data in KeystoneJS

Keystone's createItems function is a simple but powerful way to populate your database with data.

It can be used to create test fixtures or initialise your database with default content / users / etc.

There's also a shorthand syntax that can be used within update files; if you are using the auto updates feature, any file that exports a create object will automatically be wrapped and the data will be created.

createItems takes two passes at the data it is passed, first creating the items and retaining references by key (if provided) that can be used to populate relationships in the second pass. This makes it easy to create related data without asynchronous nesting (which for data creation sometimes ends up in knots).

Docs

createItems(data, callback)

The data argument should be an Object containing an Array for each List you want to populate. Each object in the array contains the data for a single item.

Each data property should match to a field path (or sub-field path) - all paths recognised by the UpdateHandler are usable.

A special property, __ref, can be set with a string value that is used to reference the item in relationships.

Relationship fields should contain either a string matching another item's __ref property, or (for many: true relationship fields) can contain an array of strings.

The callback(err, stats) function is passed the error (if there was one) and a stats object containing counts for each list of items that were created, and a special message property that can be parsed as Markdown or logged to the console.

See below for two usage examples, both independently and as an update script.

// This example demonstrates complete usage of keystone.createItems,
// and how to use its callback to log the message to the console.
function(done) {
keystone.createItems({
User: [{
'name.full': 'Jed Watson',
email: '[email protected]',
password: 'admin',
isAdmin: true,
__ref: 'jed'
}],
PostCategory: [{
name: 'Keystone JS',
__ref: 'keystone'
}, {
name: 'Node.js',
__ref: 'node'
}],
Post: [{
title: 'A draft post',
author: 'jed',
'content.brief': 'This is an example draft post.',
categories: ['keystone', 'node']
}, {
title: 'A published post',
state: 'published',
author: 'jed',
publishedDate: '2014-04-12',
'content.brief': 'This post has been published!',
categories: 'node'
}]
}, function(err, stats) {
stats && console.log(stats.message);
done(err);
});
}
// This example demonstrates the shorthand syntax you can use to
// create items in a Keystone update script.
var keystone = require('keystone');
exports.create = {
User: [{
'name.full': 'Jed Watson',
email: '[email protected]',
password: 'admin',
isAdmin: true,
__ref: 'jed'
}],
PostCategory: [{
name: 'Keystone JS',
__ref: 'keystone'
}, {
name: 'Node.js',
__ref: 'node'
}],
Post: [{
title: 'A draft post',
author: 'jed',
'content.brief': 'This is an example draft post.',
categories: ['keystone', 'node']
}, {
title: 'A published post',
state: 'published',
author: 'jed',
publishedDate: '2014-04-12',
'content.brief': 'This post has been published!',
categories: 'node'
}]
};
@andrzejs
Copy link

Hi, Jed!

I try populate data to 'post' collection and have problem, all fields is save ok, but "image" not show in db.
Plase help.
Andrzej

Post: [{
    "author" : "as",
    "content.brief": 'This is an example draft post.',
    "content.extended": 'This is an example extended post.',
    "createdOn" : Date.now(),
     "image.public_id" : "qad6ixdfbejhyy7naeqik",
      "image.version" : 1402g8548657,
      "image.signature" : "9462ty7465cdcfe41c48f533f6e7f50b5053ab14",
      "image.width" : 320,
      "image.height" : 294,
      "image.format" : "jpg",
      "image.resource_type" : "image",
      "image.url" : "http://res.cloudinary.com/xxxxxxxxxxxxxx.jpg",
    "image.secure_url" : "https://res.cloudinary.com/xxxxxxxxxxxxxxxxxx.jpg",
        "markdown.html" :"<p><img src="/images/scaffolding/120x120.png" alt="Alt text"></p>\n",
        "markdown.md" : "![Alt text](/images/scaffolding/120x120.png)",
            "slug : 'post-test"
    }]

@akoesnan
Copy link

andrzejs, were you able to populate the number type?

@akoesnan
Copy link

I figured that the number only work if its in the root.

@liuwei0514
Copy link

if user jed is already exist?

@bwlt
Copy link

bwlt commented Oct 11, 2015

Does relationships (__ref attribute) works when the field is set to required?
At the moment I get a validation error from mongoose :/

@ckromero-flintny
Copy link

Hey this worked nicely thanks!

@sarith
Copy link

sarith commented Nov 28, 2015

I'm having the same issue as @turbometalskater. Having a field that uses a __ref string set to required leads to a validation error because of the "first pass" before the relationship is resolved in the second pass. I removed the required flag and now the update step just hangs. I might be doing something else completely wrong, though. I'll continue testing and post back here if I figure it out.

Also, in the updates.js example above, is that meant to represent a standalone update file? I'm getting a keystone error that an update file needs to export a function...

@NTruchaud
Copy link

Hi everyone,
I'm new to KeystoneJS, and I'm having an issue :
I'm trying to use createItem() on a relatioship field, after importing a CSV. I turn the CSV's data into a JSON object thanks to csvtojson library, and then creating an Item based on my JSONObject.

Here is my relationship declaration :

project: { type: Types.Relationship, ref: 'Project' },

And here is my project declaration :

name: { type: Types.Text, required: true, index: true, refPath: 'project' }

But when I'm using the createItem() method, here what I have as an error message :

message: 'Relationship Info.project contains an invalid reference: "Test".' }

I hope I've been clear enough for you guys to help me,

Regards.

@robksawyer
Copy link

robksawyer commented Feb 20, 2017

It'd be nice to have a skip duplicates option that removes the duplicate keys before trying to insert.

@jsalazar24712
Copy link

Any updates on getting the "__ref" field to work on properties that are 'required'?

@dortamiguel
Copy link

Yep, why doesn't work with required fields?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment