I'm fairly new to KeystoneJS and struggle with pre-populating a database through seeds / updates. I have no problem with independent properties but struggle with properties with relationships.
I have for example a Location Model that includes photos.
var Location = new keystone.List('Location', {
sortable: true,
autokey: {
path: 'slug',
from: 'name',
unique: true
}
});
Location.add({
name: {
type: Types.Text,
required: true,
initial: true
},
photos: {
type: Types.Relationship,
ref: 'Photo',
many: true
}
}
and the Photo Model is as such:
var Photo = new keystone.List('Photo', {
autokey: {
path: 'slug',
from: 'title',
unique: true
}
});
Photo.add({
title: {
type: Types.Text,
initial: true,
index: true
},
image: {
type: Types.CloudinaryImage,
required: true,
initial: false
}
});
Photo.relationship({
ref: 'Location',
path: 'photos',
refPath: 'photos'
});
Within the update folder I'm trying to seed the database with pre-loaded data. Both Location and Photo models get populated individually but I am failing to pre-populate the relationship within both within the Admin UI and lacks knowledge on how to solve. I did quite some research, tried different things such as using __ref
and _ids
but couldn't make it work. I could not find the answer within the KeystoneJS documentation either. Maybe there is something obvious that I'm actually missing.
exports.create = {
Location: [
{
name: 'London',
photos: [
// <-- how to do it here?
]
},
{
name: 'New York',
photos: [
// <-- how to do it here?
]
}
]
};
Would anyone know the right way to pre-populate KeystoneJs database relationships? Thank you very much.
I managed to solve by mapping through the photos and replace by the actual photo found by title. Here is how I did in case it can help someone else:
exports = module.exports = function (next) {
Promise.all([
{
name: 'London',
photos: ['london_1', 'london_2']
},
{
name: 'New York',
photos: ['new_york_1', 'new_york_2']
}
].map(function (location) {
var _photos = location.photos || [];
location.photos = [];
return Promise.all([
_photos.map(function (title) {
return Photo.model.findOne({ title: title })
.then(function (photo) {
location.photos.push(photo);
});
})
])
.then(function () {
new Location.model(location).save();
});
}))
.then(function () {
next();
})
.catch(next);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.