Keystone JS - Update / seeding / with Relationship - javascript

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);
};

Related

Filter the populated data and then paginate in Mongodb

Hello I am trying to populate the data and then trying to paginate that data.
Here is the example
Schema A (Users)
{
name: 'Demo',
postId: 'someObjectId',
}
Schema B (Posts)
{
id: 'someObjectId',
postName: 'Post 1',
date: 'date of creation'
}
Here is my code
const users = UserModel.find({
name: 'Demo'
}).populate({
path: 'postId',
select: 'date',
match: {'postId.date' : {$lt: 'today'}}
}).page(pagination).limit(20)
Not getting the result needed. Can someone point out what's wrong?
NOTE: I have just given the overview. Please don't take it as real code. I know I haven't written what we would write in javascript
A populate have following things:
Post.find({})
.populate([
// here array is for our memory.
// because may need to populate multiple things
{
path: 'user',
select: 'name',
model:'User',
options: {
sort:{ },
skip: 5,
limit : 10
},
match:{
// filter result in case of multiple result in populate
// may not useful in this case
}
}
]);
.exec((err, results)=>{
console.log(err, results)
});

Creating a GET request that displays all reviews based on the item value of what they reviewed

I am currently working on making a GET request on my backend that maps out all reviews based on the item number attached to the review. I've made a few dummy reviews that share the same item number (but have different _id values) and am trying to figure out how to create this GET request.
I can get all reviews to map out in general but not by item number
My current code block is this and I'm getting the error
TypeError: Cannot read properties of undefined (reading 'get')
router.get("/:id", async (req, res) => {
const populateQuery = [
{
path: "user",
select: ["username"],
},
{
path: "reviews",
select: ["item"],
populate: { path: "user", select: ["username"] },
},
]
const reviews = await Review.find({})
response.json(reviews.map((review) => review.toJSON()))
})
An example review would be:
_id:615323ee97dc7d1960350e33
text:"This could've been worse but I'm glad they actually tried this time"
item:168
_id:615b95dfd6a4fc3814139ad4
text:"Delete this review and this game"
item:168
_id:615b968e9dafdbead0de3fde
text:"Witcher is amazing"
item:4062
Basically, I want the function to show the ones with item:168 mapped out and separate from the Witcher review.
My model schema for reviews is this
import mongoose from "mongoose"
const { ObjectId } = mongoose.Schema.Types
const reviewSchema = new mongoose.Schema(
{
text: {
type: String,
required: true,
maxlength: 500,
},
author: {
type: ObjectId,
ref: "User",
},
created: {
type: Date,
default: Date.now,
},
item: {
type: Number,
required: true,
}
},
{ timestamps: true }
)
const Review = mongoose.model("Review", reviewSchema)
export default Review

Dynamically return config value (node.js)

I'm building a content middleware which gather contents from our external publishers. The publishers will share their contents either in rss or json and the key/value field would be different from each other. To make thing easier, I created a config file where I can pre-defined the key/value and the feed type. The problem is, how can I dynamically return this config value based on publishers name.
Example: To get Publisher #1 feed type, I just can use config.articles.rojak_daily.url_feed
my config file /config/index.js
module.exports = {
batch:100,
mysql: {
database: process.env.database,
host: process.env.host,
username: process.env.username,
password: process.env.password
},
articles:{
rojak_daily:{ // Publisher 1
url: 'xxx',
url_feed: 'rss',
id: null,
Name: 'title',
Description: 'description',
Link: 'link',
DatePublishFrom: 'pubDate',
LandscapeImage: 's3image',
SiteName: 'Rojak Daily',
SiteLogo: null
},
rojak_weekly:{ // publisher 2
url: 'xxx',
url_feed: 'json',
id: null,
Name: 'Name',
Description: 'Desc',
Link: 'link',
DatePublishFrom: 'pubDate',
LandscapeImage: 's3image',
SiteName: 'Rojak Weekly',
SiteLogo: null
}
}
}
my main application script
const config = require('#config'); // export from config file
class Main {
constructor(){
this.publishers = ['rojak_daily','rojak_weekly'];
}
// Main process
async startExport(){
try{
for(let publisher of this.publishers){
const feedType = await this.getFeedType(publisher)
const result = (feedType == 'rss')? await this.rss.start(publisher): await this.json.start(publisher)
return result
}
}catch(err){
console.log("Error occured: ", err)
}
}
// Get feed type from config
async getFeedType(publisher){
return await config.articles.rojak_daily.url_feed;
// this only return publisher 1 url feed.
// my concern is to dynamically passing variable
// into this config file (example: config.articles.<publisher>.url_feed)
}
}
module.exports = Main
async getFeedType(publisher){
return await config.articles[publisher].url_feed;
}
You can access properties of objects by variable
You could either loop over the articles by using Object.entries(articles) or Object.values(articles) in conjunction with Array.prototype.forEach(), or since you already have the name of the publisher you could access that entry with config.articles[publisher].url_feed, like so:
const config = {
articles: {
rojak_daily: { // Publisher 1
url: 'xxx',
url_feed: 'rss',
id: null,
Name: 'title',
Description: 'description',
Link: 'link',
DatePublishFrom: 'pubDate',
LandscapeImage: 's3image',
SiteName: 'Rojak Daily',
SiteLogo: null
},
rojak_weekly: { // publisher 2
url: 'xxx',
url_feed: 'json',
id: null,
Name: 'Name',
Description: 'Desc',
Link: 'link',
DatePublishFrom: 'pubDate',
LandscapeImage: 's3image',
SiteName: 'Rojak Weekly',
SiteLogo: null
}
}
}
const publishers = ['rojak_daily', 'rojak_weekly']
function getFeedType(publisher) {
return config.articles[publisher].url_feed;
}
publishers.forEach(publisher => console.log(getFeedType(publisher)));

Query and map one-way referenced children and sub-children from a parent with mongoose in Keystone.js

I got three models with one-to-many relationships. Simple tree. What I need is a simple, efficient way to query a structured relationship tree, preferably similar to mongoose's .populate() which I cant't use since I don't have id's on the parent model. I suppose keeping children ids on parent would be efficient, but Keystone doesn't provide this functionality by default and I am unable to write an update callback to control relational changes. I tried and wasted too much time, finding myself astray while maybe what I'm trying to achieve is much easier, but I just can't see it.
Here's the stripped code:
Category model
Category.add({
name: { type: String}
});
Category.relationship({ path: 'sections', ref: 'Section', refPath: 'category' });
Section model, child of a category
Section.add({
name: { type: String, unique: true, required: true}
category: { type: Types.Relationship, ref: 'Category', many: false}
});
Section.relationship({ path: 'articles', ref: 'Article', refPath: 'section'});
Article model, child of the Section
Article.add({
name: { type: String, required: true}
section: { type: Types.Relationship, ref: 'Section', many: false }
});
I want to get a structured view of a category with all children and their respective sub-children like this:
[ { _id: 57483c6bad451a1f293486a0,
name: 'Test Category',
sections: [
{ _id: 57483cbbad451a1f293486a1,
name: 'Test Section',
articles: [
{ _id: 57483c6bad451a1f293486a0,
name: 'Test Category' }
]
]
} ]
So that's how I did it. Not at all efficient but at least it's working. I didn't put anything in first-level parent since I need only one.
// Load current category
view.on('init', function (next) {
var q = keystone.list('Category').model.findOne({
key: locals.filters.category
});
q.exec(function (err, result) {
if (err || !results.length) {
return next(err);
}
locals.data.category = result;
locals.section = locals.data.category.name.toLowerCase();
next(err);
});
});
// Load sections and articles inside of them
view.on('init', function (next) {
var q = keystone.list('Section').model.find().where('category').in([locals.data.category]).sort('sortOrder').exec(function(err, results) {
if (err || !results.length) {
return next(err);
}
async.each(results, function(section, next) {
keystone.list('Article').model.find().where('section').in([section.id]).sort('sortOrder').exec(function(err, articles){
var s = section;
if (articles.length) {
s.articles = articles;
locals.data.sections.push(s);
} else {
locals.data.sections.push(s);
}
});
}, function(err) {
next(err);
});
next(err);
});
});
But now I'm getting another issue. I'm using Jade 1.11.0 for templates and sometimes it doesnt't show the data in the view.
I will post another question for this issue.

How to add a property to an entity dynamically?

How do you add a property to an entity dynamically? I've been looking, but haven't found anything.
For example, I have this model definition (I'm using the WebSQL provider):
$data.Entity.extend('$db.Types.Person', {
id: { type: 'int', key: true, computed: true },
name: { type: 'string' }
});
$data.EntityContext.extend('$db.Types.DBContext', {
Persons: { type: $data.EntitySet, elementType: $db.Types.Person},
});
At some point I need to extend my model with new properties. Initially I don't know these properties' names.
The syntax is very simple for this, but the background info is more important, please read the whole answer before you reuse the snippet.
The YourType can be extended with new fields using the YourType.addMember() function. See this example snippet:
$data.Entity.extend('Product', {
id: { type: 'int', key: true, computed: true },
Name: { type: 'string' }
});
$data.EntityContext.extend('Northwind', {
Products: { type: $data.EntitySet, elementType: Product},
});
Product.addMember('Description', {
type:'string',
key: false,
computed: false,
required: false
});
var context = new Northwind({provider: 'webSql', databaseName: 'Northwind'});
context.onReady(function() {
var product1 = new Product({ Name: 'Beer', Description: 'tasty'});
context.Products.add(product1);
context.saveChanges(function(result) {
//check the content of WebSQL DB
console.log(product1);
});
});
You can user the addMember() only before creating an instance of the context.
Important info:
There is no data migration/merge by in the library, and the default behavior on schema modification for webSql is to drop&re-create the DB. As IndexedDB isn't bound to a schema, the existing records won't be dropped. Make a try by running this code and adding more fields, here is a working JSFiddle.
The real solution is to use Schema Evolution module of JayData Pro to manage the changes in your data model.

Categories