how i can merge nested array with in a new object with ramda? - ramda.js

There is an object that holds variables related to the UI.
const data = [
{ color: [{ primary: "#444", secondary: "#dede", light: "#fff" }] },
{ size: [12,14,16,18,20] },
...
];
I want to make this object a single array like:
const UI = [
{ colorPrimary: "#444" },
{ colorSecondary: "#dede" },
{ colorLight: "#fff" },
{ size0: 12 },
{ size1: 14 },
{ size2: 16 },
{ size3: 18 },
{ size4: 20 },
...
];
How can I do this with ramda ?

I don't have a clean way to do it with the data as supplied because of the reason expressed in my comment:
How would you distinguish between a property like color, where you seem to ignore the array holding the data, and one like size, where the array indices become part of the keys?
But with just a minor tweak to your data, to this:
const data = [
{ color: { primary: "#444", secondary: "#dede", light: "#fff" } },
{ size: [12,14,16,18,20] },
];
It's reasonably straightforward:
const initialCap = str => toUpper(head(str)) + tail(str);
const collectProps = pipe(
map(map(toPairs)),
apply(merge),
mapObjIndexed((pairs, key) => map(
pair => objOf(key + initialCap(pair[0]), pair[1]), pairs
)),
values,
apply(concat)
);
collectProps(data);
You can see this in action on the Ramda REPL.
I don't know anything about the source of your data, so I have no idea if this is at all possible for you to manage. But if you can, this looks like it should work.

Related

How to configure Typegoose with GraphQL to reference subdocument to part of another document? [duplicate]

I'm pretty new to Mongoose and MongoDB in general so I'm having a difficult time figuring out if something like this is possible:
Item = new Schema({
id: Schema.ObjectId,
dateCreated: { type: Date, default: Date.now },
title: { type: String, default: 'No Title' },
description: { type: String, default: 'No Description' },
tags: [ { type: Schema.ObjectId, ref: 'ItemTag' }]
});
ItemTag = new Schema({
id: Schema.ObjectId,
tagId: { type: Schema.ObjectId, ref: 'Tag' },
tagName: { type: String }
});
var query = Models.Item.find({});
query
.desc('dateCreated')
.populate('tags')
.where('tags.tagName').in(['funny', 'politics'])
.run(function(err, docs){
// docs is always empty
});
Is there a better way do this?
Edit
Apologies for any confusion. What I'm trying to do is get all Items that contain either the funny tag or politics tag.
Edit
Document without where clause:
[{
_id: 4fe90264e5caa33f04000012,
dislikes: 0,
likes: 0,
source: '/uploads/loldog.jpg',
comments: [],
tags: [{
itemId: 4fe90264e5caa33f04000012,
tagName: 'movies',
tagId: 4fe64219007e20e644000007,
_id: 4fe90270e5caa33f04000015,
dateCreated: Tue, 26 Jun 2012 00:29:36 GMT,
rating: 0,
dislikes: 0,
likes: 0
},
{
itemId: 4fe90264e5caa33f04000012,
tagName: 'funny',
tagId: 4fe64219007e20e644000002,
_id: 4fe90270e5caa33f04000017,
dateCreated: Tue, 26 Jun 2012 00:29:36 GMT,
rating: 0,
dislikes: 0,
likes: 0
}],
viewCount: 0,
rating: 0,
type: 'image',
description: null,
title: 'dogggg',
dateCreated: Tue, 26 Jun 2012 00:29:24 GMT
}, ... ]
With the where clause, I get an empty array.
With a modern MongoDB greater than 3.2 you can use $lookup as an alternate to .populate() in most cases. This also has the advantage of actually doing the join "on the server" as opposed to what .populate() does which is actually "multiple queries" to "emulate" a join.
So .populate() is not really a "join" in the sense of how a relational database does it. The $lookup operator on the other hand, actually does the work on the server, and is more or less analogous to a "LEFT JOIN":
Item.aggregate(
[
{ "$lookup": {
"from": ItemTags.collection.name,
"localField": "tags",
"foreignField": "_id",
"as": "tags"
}},
{ "$unwind": "$tags" },
{ "$match": { "tags.tagName": { "$in": [ "funny", "politics" ] } } },
{ "$group": {
"_id": "$_id",
"dateCreated": { "$first": "$dateCreated" },
"title": { "$first": "$title" },
"description": { "$first": "$description" },
"tags": { "$push": "$tags" }
}}
],
function(err, result) {
// "tags" is now filtered by condition and "joined"
}
)
N.B. The .collection.name here actually evaluates to the "string" that is the actual name of the MongoDB collection as assigned to the model. Since mongoose "pluralizes" collection names by default and $lookup needs the actual MongoDB collection name as an argument ( since it's a server operation ), then this is a handy trick to use in mongoose code, as opposed to "hard coding" the collection name directly.
Whilst we could also use $filter on arrays to remove the unwanted items, this is actually the most efficient form due to Aggregation Pipeline Optimization for the special condition of as $lookup followed by both an $unwind and a $match condition.
This actually results in the three pipeline stages being rolled into one:
{ "$lookup" : {
"from" : "itemtags",
"as" : "tags",
"localField" : "tags",
"foreignField" : "_id",
"unwinding" : {
"preserveNullAndEmptyArrays" : false
},
"matching" : {
"tagName" : {
"$in" : [
"funny",
"politics"
]
}
}
}}
This is highly optimal as the actual operation "filters the collection to join first", then it returns the results and "unwinds" the array. Both methods are employed so the results do not break the BSON limit of 16MB, which is a constraint that the client does not have.
The only problem is that it seems "counter-intuitive" in some ways, particularly when you want the results in an array, but that is what the $group is for here, as it reconstructs to the original document form.
It's also unfortunate that we simply cannot at this time actually write $lookup in the same eventual syntax the server uses. IMHO, this is an oversight to be corrected. But for now, simply using the sequence will work and is the most viable option with the best performance and scalability.
Addendum - MongoDB 3.6 and upwards
Though the pattern shown here is fairly optimized due to how the other stages get rolled into the $lookup, it does have one failing in that the "LEFT JOIN" which is normally inherent to both $lookup and the actions of populate() is negated by the "optimal" usage of $unwind here which does not preserve empty arrays. You can add the preserveNullAndEmptyArrays option, but this negates the "optimized" sequence described above and essentially leaves all three stages intact which would normally be combined in the optimization.
MongoDB 3.6 expands with a "more expressive" form of $lookup allowing a "sub-pipeline" expression. Which not only meets the goal of retaining the "LEFT JOIN" but still allows an optimal query to reduce results returned and with a much simplified syntax:
Item.aggregate([
{ "$lookup": {
"from": ItemTags.collection.name,
"let": { "tags": "$tags" },
"pipeline": [
{ "$match": {
"tags": { "$in": [ "politics", "funny" ] },
"$expr": { "$in": [ "$_id", "$$tags" ] }
}}
]
}}
])
The $expr used in order to match the declared "local" value with the "foreign" value is actually what MongoDB does "internally" now with the original $lookup syntax. By expressing in this form we can tailor the initial $match expression within the "sub-pipeline" ourselves.
In fact, as a true "aggregation pipeline" you can do just about anything you can do with an aggregation pipeline within this "sub-pipeline" expression, including "nesting" the levels of $lookup to other related collections.
Further usage is a bit beyond the scope of what the question here asks, but in relation to even "nested population" then the new usage pattern of $lookup allows this to be much the same, and a "lot" more powerful in it's full usage.
Working Example
The following gives an example using a static method on the model. Once that static method is implemented the call simply becomes:
Item.lookup(
{
path: 'tags',
query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } }
},
callback
)
Or enhancing to be a bit more modern even becomes:
let results = await Item.lookup({
path: 'tags',
query: { 'tagName' : { '$in': [ 'funny', 'politics' ] } }
})
Making it very similar to .populate() in structure, but it's actually doing the join on the server instead. For completeness, the usage here casts the returned data back to mongoose document instances at according to both the parent and child cases.
It's fairly trivial and easy to adapt or just use as is for most common cases.
N.B The use of async here is just for brevity of running the enclosed example. The actual implementation is free of this dependency.
const async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/looktest');
const itemTagSchema = new Schema({
tagName: String
});
const itemSchema = new Schema({
dateCreated: { type: Date, default: Date.now },
title: String,
description: String,
tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]
});
itemSchema.statics.lookup = function(opt,callback) {
let rel =
mongoose.model(this.schema.path(opt.path).caster.options.ref);
let group = { "$group": { } };
this.schema.eachPath(p =>
group.$group[p] = (p === "_id") ? "$_id" :
(p === opt.path) ? { "$push": `$${p}` } : { "$first": `$${p}` });
let pipeline = [
{ "$lookup": {
"from": rel.collection.name,
"as": opt.path,
"localField": opt.path,
"foreignField": "_id"
}},
{ "$unwind": `$${opt.path}` },
{ "$match": opt.query },
group
];
this.aggregate(pipeline,(err,result) => {
if (err) callback(err);
result = result.map(m => {
m[opt.path] = m[opt.path].map(r => rel(r));
return this(m);
});
callback(err,result);
});
}
const Item = mongoose.model('Item', itemSchema);
const ItemTag = mongoose.model('ItemTag', itemTagSchema);
function log(body) {
console.log(JSON.stringify(body, undefined, 2))
}
async.series(
[
// Clean data
(callback) => async.each(mongoose.models,(model,callback) =>
model.remove({},callback),callback),
// Create tags and items
(callback) =>
async.waterfall(
[
(callback) =>
ItemTag.create([{ "tagName": "movies" }, { "tagName": "funny" }],
callback),
(tags, callback) =>
Item.create({ "title": "Something","description": "An item",
"tags": tags },callback)
],
callback
),
// Query with our static
(callback) =>
Item.lookup(
{
path: 'tags',
query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } }
},
callback
)
],
(err,results) => {
if (err) throw err;
let result = results.pop();
log(result);
mongoose.disconnect();
}
)
Or a little more modern for Node 8.x and above with async/await and no additional dependencies:
const { Schema } = mongoose = require('mongoose');
const uri = 'mongodb://localhost/looktest';
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
const itemTagSchema = new Schema({
tagName: String
});
const itemSchema = new Schema({
dateCreated: { type: Date, default: Date.now },
title: String,
description: String,
tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]
});
itemSchema.statics.lookup = function(opt) {
let rel =
mongoose.model(this.schema.path(opt.path).caster.options.ref);
let group = { "$group": { } };
this.schema.eachPath(p =>
group.$group[p] = (p === "_id") ? "$_id" :
(p === opt.path) ? { "$push": `$${p}` } : { "$first": `$${p}` });
let pipeline = [
{ "$lookup": {
"from": rel.collection.name,
"as": opt.path,
"localField": opt.path,
"foreignField": "_id"
}},
{ "$unwind": `$${opt.path}` },
{ "$match": opt.query },
group
];
return this.aggregate(pipeline).exec().then(r => r.map(m =>
this({ ...m, [opt.path]: m[opt.path].map(r => rel(r)) })
));
}
const Item = mongoose.model('Item', itemSchema);
const ItemTag = mongoose.model('ItemTag', itemTagSchema);
const log = body => console.log(JSON.stringify(body, undefined, 2));
(async function() {
try {
const conn = await mongoose.connect(uri);
// Clean data
await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()));
// Create tags and items
const tags = await ItemTag.create(
["movies", "funny"].map(tagName =>({ tagName }))
);
const item = await Item.create({
"title": "Something",
"description": "An item",
tags
});
// Query with our static
const result = (await Item.lookup({
path: 'tags',
query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } }
})).pop();
log(result);
mongoose.disconnect();
} catch (e) {
console.error(e);
} finally {
process.exit()
}
})()
And from MongoDB 3.6 and upward, even without the $unwind and $group building:
const { Schema, Types: { ObjectId } } = mongoose = require('mongoose');
const uri = 'mongodb://localhost/looktest';
mongoose.Promise = global.Promise;
mongoose.set('debug', true);
const itemTagSchema = new Schema({
tagName: String
});
const itemSchema = new Schema({
title: String,
description: String,
tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]
},{ timestamps: true });
itemSchema.statics.lookup = function({ path, query }) {
let rel =
mongoose.model(this.schema.path(path).caster.options.ref);
// MongoDB 3.6 and up $lookup with sub-pipeline
let pipeline = [
{ "$lookup": {
"from": rel.collection.name,
"as": path,
"let": { [path]: `$${path}` },
"pipeline": [
{ "$match": {
...query,
"$expr": { "$in": [ "$_id", `$$${path}` ] }
}}
]
}}
];
return this.aggregate(pipeline).exec().then(r => r.map(m =>
this({ ...m, [path]: m[path].map(r => rel(r)) })
));
};
const Item = mongoose.model('Item', itemSchema);
const ItemTag = mongoose.model('ItemTag', itemTagSchema);
const log = body => console.log(JSON.stringify(body, undefined, 2));
(async function() {
try {
const conn = await mongoose.connect(uri);
// Clean data
await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()));
// Create tags and items
const tags = await ItemTag.insertMany(
["movies", "funny"].map(tagName => ({ tagName }))
);
const item = await Item.create({
"title": "Something",
"description": "An item",
tags
});
// Query with our static
let result = (await Item.lookup({
path: 'tags',
query: { 'tagName': { '$in': [ 'funny', 'politics' ] } }
})).pop();
log(result);
await mongoose.disconnect();
} catch(e) {
console.error(e)
} finally {
process.exit()
}
})()
what you are asking for isn't directly supported but can be achieved by adding another filter step after the query returns.
first, .populate( 'tags', null, { tagName: { $in: ['funny', 'politics'] } } ) is definitely what you need to do to filter the tags documents. then, after the query returns you'll need to manually filter out documents that don't have any tags docs that matched the populate criteria. something like:
query....
.exec(function(err, docs){
docs = docs.filter(function(doc){
return doc.tags.length;
})
// do stuff with docs
});
Try replacing
.populate('tags').where('tags.tagName').in(['funny', 'politics'])
by
.populate( 'tags', null, { tagName: { $in: ['funny', 'politics'] } } )
Update: Please take a look at the comments - this answer does not correctly match to the question, but maybe it answers other questions of users which came across (I think that because of the upvotes) so I will not delete this "answer":
First: I know this question is really outdated, but I searched for exactly this problem and this SO post was the Google entry #1. So I implemented the docs.filter version (accepted answer) but as I read in the mongoose v4.6.0 docs we can now simply use:
Item.find({}).populate({
path: 'tags',
match: { tagName: { $in: ['funny', 'politics'] }}
}).exec((err, items) => {
console.log(items.tags)
// contains only tags where tagName is 'funny' or 'politics'
})
Hope this helps future search machine users.
After having the same problem myself recently, I've come up with the following solution:
First, find all ItemTags where tagName is either 'funny' or 'politics' and return an array of ItemTag _ids.
Then, find Items which contain all ItemTag _ids in the tags array
ItemTag
.find({ tagName : { $in : ['funny','politics'] } })
.lean()
.distinct('_id')
.exec((err, itemTagIds) => {
if (err) { console.error(err); }
Item.find({ tag: { $all: itemTagIds} }, (err, items) => {
console.log(items); // Items filtered by tagName
});
});
#aaronheckmann 's answer worked for me but I had to replace return doc.tags.length; to return doc.tags != null; because that field contain null if it doesn't match with the conditions written inside populate.
So the final code:
query....
.exec(function(err, docs){
docs = docs.filter(function(doc){
return doc.tags != null;
})
// do stuff with docs
});

Using Custom Sort with Track Scores set to True is still showing score as null

So I'm setting a default query in my React Native app. Essentially I'm trying to set a sortOrder based on the elementOrder values. My partner used this same piece of code in his web app and it works for him. It doesn't seem to work on my end. The score exists if I remove the custom sort, which is normal due to what I've read in the docs. When I'm using a custom sort, then I should add track_scores: true. My score is still coming up as null.
I am not sure how to debug this situation. Can someone point me in the right direction? Thanks! Here's my code and let me know if you need to see anything. Unfortunately I don't have access to Kibana. I'm just console logging the list item and it's properties.
const defaultQueryConfig = {
track_scores: true,
sort: {
_script: {
type: 'number',
script: {
lang: 'painless',
source: `
int sortOrder = 0;
if (doc['elementOrder'].value == 1) {sortOrder = 3}
else if (doc['elementOrder'].value == 3) {sortOrder = 2}
else if (doc['elementOrder'].value == 2) {sortOrder = 1}
sortOrder;
`,
},
order: 'desc',
},
},
query: {
function_score: {
query: {
match_all: {},
},
functions: [
{
filter: {
match: {
categoryType: 'earth',
},
},
weight: 100,
},
{
filter: {
match: {
categoryType: 'water',
},
},
weight: 90,
},
{
filter: {
match: {
categoryType: 'fire',
},
},
weight: 80,
},
{
filter: {
match: {
thingExists: false,
},
},
weight: 2,
},
],
score_mode: 'multiply',
},
},
};

How to loop thru 3 arrays using only one v-for?

I have 3 arrays in my Vuex State. How to loop thru all of them using ONE v-for? For instance:
export const stepOne = {
state: {
textfields: [
{
value: "",
label: "weight",
},
],
textfieldTire: {
value: "",
label: "Tire radius",
},
textfieldDocument: [
{
value: "",
label: "Document",
},
],
},
}
Thats how I'm displaying them, but it only shows "textfields" array. How to output data without using multiple v-for?
.check-data
.table(
v-for='(item, idx) in $store.state.stepOne.textfield'
:key='idx'
)
.label
| {{$store.state.stepOne.textfield[idx].label}}
.value
| {{$store.state.stepOne.textfield[idx].value}}
A computed property with Array's concat method should do the job.
export default {
/* other properties */
computed: {
textfields () {
const { textfield, textfieldTire, textfieldDocument } = this.$store.state.stepOne
return textfield.concat(textfieldTire, textfieldDocument)
}
}
}
Then change the array you iterating through to the one we just created.
.check-data
.table(
v-for='(item, idx) in textfields'
:key='idx'
)
.label
| {{item.label}}
.value
| {{item.value}}

Generic Grouping of objects properties

I'm trying to group this object by name, so in fine I would be able to distinguish all names 'duval' from 'lulu':
const groupName = R.groupBy(R.prop('name'), [data]);
But this won't work on:
let data = {
benj: {
content : undefined,
name : 'duval',
complete: false,
height : 181
},
joy: {
content : undefined,
name : 'duval',
complete: true
},
kaori: {
content : undefined,
name : 'lulu',
complete: true
},
satomi: {
content : undefined,
name : 'lulu',
complete: true
}
}
Should I change the format of my object, or is there a way to do it in this kind of object ?
Passing [data] to groupBy is not going to help much. You want to group a list containing a single item. The fact that that item has properties like 'bennj' and 'joy' rather than 'name' is only part of the issue.
You can get something that will work, I think, if this output would be useful:
{
duval: {
benj: {
content: undefined,
name: "duval",
complete: false,
height: 181
},
joy: {
content: undefined,
name: "duval",
complete: true
}
},
lulu: {
kaori: {
content: undefined,
name: "lulu",
complete: true
},
satomi: {
content: undefined,
name: "lulu",
complete: true
}
}
}
But it's a bit more involved:
compose(map(fromPairs), groupBy(path([1, 'name'])), toPairs)(data)
toPairs converts the data to a list of elements something like this:
[
"benj",
{
complete: false,
content: undefined,
height: 181,
name: "duval"
}
]
then groupBy(path[1, 'name']) does the grouping you're looking to do, by finding the name on the object at index 1 in this list.
And finally map(fromPairs) will turn these lists of lists back into objects.
It's not a particularly elegant solution, but it's fairly typical when you want to do list processing on something that's not really a list.

sencha touch dynamic chart

in Sencha Touch 2.1 how can I load the chart dynamically from json, also with dynamic fields store, chart axes, and chart series,
I know maybe this is too much, but I need to display many kind of data, If I create 1 chart component for each display means I have to create more than 15 chart component, I'm afraid it get bloated
I did not complete this dynamically, but I made it seem dynamic.
I first request a user to fill out a form.
I also have multiple panels that holds charts with empty stores, in the form of several different layouts.
Based on the user's form, I show and hide panels, or chart when they need to be displayed only after loading the store with the required data.
yes it is bulky, and they are static, but I found it slightly easier to handle than dynamically loading.
EDIT
After thinking,
have you tried a function like
function dynamiccharts(var1, var2, var3){
return Ext.chart.Chart({
....
})
}
variables would include things like data, url, store or etc.
This is my example creating a chart on controller inside a panel: axis, series, store fields, url are became parameters, PAR_FORM is global variable showing the difference between views, I'm using this code for another chart (Column, Pie)
Ext.define("Geis.controller.app", {
extend: "Ext.app.Controller",
config: {
refs: {
mainview: 'mainview',
barchartview: 'barchartview',
btnShowChartAnggaran: '#btnShowChartAnggaran'
},
control: {
'btnShowChartAnggaran': {
tap: 'onShowChartAnggaran'
}
}
}
createBarChart: function(fields, series_xfield, series_yfield, url) {
this.getBarchartview().add(new Ext.chart.CartesianChart({
id: 'barchartgenerateview',
store: {
fields: fields,
proxy: {
type: 'jsonp',
url: url
}
},
background: 'white',
flipXY: true,
colors: Geis.view.ColorPatterns.getBaseColors(),
interactions: [
{
type: 'panzoom',
axes: {
"left": {
allowPan: true,
allowZoom: true
},
"bottom": {
allowPan: true,
allowZoom: true
}
}
},
'itemhighlight'
],
series: [{
type: 'bar',
xField: series_xfield,
yField: series_yfield,
highlightCfg: {
strokeStyle: 'red',
lineWidth: 3
},
style: {
stroke: 'rgb(40,40,40)',
maxBarWidth: 30
}
}],
axes: [{
type: 'numeric',
position: 'bottom',
fields: series_yfield,
grid: {
odd: {
fill: '#e8e8e8'
}
},
label: {
rotate: {
degrees: -30
}
},
maxZoom: 1
},
{
type: 'category',
position: 'left',
fields: series_xfield,
maxZoom: 4
}]
}));
Ext.getCmp('barchartgenerateview').getStore().load();
},
onShowChartAnggaran: function() {
this.getBarchartview().remove(Ext.getCmp('barchartgenerateview'), true);
if (PAR_FORM == 'Dana Anggaran') {
this.createBarChart(['kode', 'keterangan', 'nilai'], 'keterangan', 'nilai',
Geis.util.Config.getBaseUrl() + 'anggaran/laporan/json/get_dana_anggaran_json/');
} else if (PAR_FORM == 'Alokasi Anggaran') {
this.createBarChart(['kode', 'keterangan', 'belanja_pegawai', 'belanja_barang', 'belanja_modal'],
'keterangan', ['belanja_pegawai', 'belanja_barang', 'belanja_modal'],
Geis.util.Config.getBaseUrl() + 'anggaran/laporan/json/get_alokasi_json/');
}
this.getMainview().animateActiveItem(1, {type:'slide', direction:'left'});
}
});
base on my experiment if you want to activate the interactions features you need to set the chart id dynamically too, for example by creating Global Counter Variable