Mongoose schema infinite nesting - node.js

I'm having some trouble creating a model that describes the object that I want to store in mongoDB.
This is the object:
simple: [
{
label: 'Satisfied customers',
children: [
{
label: 'Good food',
children: [
{ label: 'Quality ingredients' },
{ label: 'Good recipe' }
]
},
{
label: 'Good service (disabled node)',
children: [
{ label: 'Prompt attention' },
{ label: 'Professional waiter' }
]
},
{
label: 'Pleasant surroundings',
children: [
{ label: 'Happy atmosphere' },
{ label: 'Good table presentation' },
{ label: 'Pleasing decor' }
]
}
]
}
]
This is data that is input to a QTree: https://quasar.dev/vue-components/tree
I want to model this but this object can in theory expand indefinitely as each child can have children of it's own and so on. Is there a way to do this nicely in a Mongoose Schema? My search so far turned up empty.
Here is what I have now:
simple: [{
_id: false,
label: String,
children: [{
_id: false,
label: String,
}]
}]
I can ofcourse choose to limit the depth to a certain amount (say 5) and put that amount of nesting in my schema, but I'm trying to find a more elegant solution so that I dont have to do that.

Related

How to Remove Specific Text / String Out of Array Object Values

I am using Node.js 16.17 and Express.
Forgive me if this is answered elsewhere, if a solution exists elsewhere, please point me in that direction.
On my server side, I have an array with objects with properties and their values. I want to be able to remove specific text/string from the property values.
What I Have
I currently have an array with objects (and sometimes arrays and object nested within):
DataArray =
[
{
page: {
results: [
{
id: '1234',
title: 'TextIWantA **(Text) I Dont Want**',
children: {
page: {
results: [
{
id: '5678',
title: 'ChildA TextIWant **(Text I) Dont Want**',
},
{
id: '9101',
title: 'ChildB TextIWant **(Text I) Dont Want**',
children: {
page: {
results: [
{
id: 'abcd',
title: 'GrandchildA TextIWant **(Text I (Dont) Want**',
}
]
}
}
},
],
},
},
},
{
id: '1121',
title: 'TextIWantB **(Text) I Dont Want**',
}
]
}
}
]
I am able to flatten this structure with this function:
function flatten(arr) {
const flattened = []
for (const { children, ...element } of arr) {
flattened.push(element)
if (children) {
flattened.push(...flatten(children.page.results))
}
}
return flattened;
}
const flat = [{ page: { results: flatten(DataArray[0].page.results) } }]
console.log(flat[0].page.results)
The returned data is:
[
{ id: '1234', 'page', title: 'TextIWantA **(Text) I Dont Want**' },
{ id: '5678', 'page', title: 'ChildA TextIWant **(Text I) Dont Want**' },
{ id: '9101', 'page', title: 'ChildB TextIWant **(Text I) Dont Want**' },
{ id: 'abcd', 'page', title: 'GrandchildA TextIWant **(Text I (Dont) Want**' },
{ id: '1121', 'page', title: 'TextIWantB **(Text) I Dont Want**' }
]
I am making an assumption that I have to change my text to a string in order to replace it then parse it again to turn back into an object. I'm happy to learn my assumption is true or incorrect, if incorrect, how to fix to be able to remove text.
So if I try to do a replace using the following, 1) it does not work and 2) it does not differentiate for the different text to remove (perhaps I just run multiple/different replaces/filters?):
const veryFlat = flat;
var veryFlatData = veryFlat.map(function(x){return x.toString().replace(/ **(Text) I Dont Want**/g, '');});
var removedTextData= JSON.parse(veryFlatData);
console.log(removedTextData);
Desired Result
I want to be able to remove all of the variances of Text I Dont Want, so the end result would look like (of now it will be flattened as seen above)
DataArray =
[
{
page: {
results: [
{
id: '1234',
title: 'TextIWantA',
children: {
page: {
results: [
{
id: '5678',
title: 'ChildA TextIWant',
},
{
id: '9101',
title: 'ChildB TextIWant',
children: {
page: {
results: [
{
id: 'abcd',
title: 'GrandchildA TextIWant',
}
]
}
}
},
],
},
},
},
{
id: '1121',
title: 'TextIWantB',
}
]
}
}
]
Each title is unique and I don't seem able to find anything to even say I've tried this or that.
I don't want to use .startswith or .length or .index and would prefer to avoid regex, and the example above using .replace doesn't seem to work.
How do I reach into these property values and rip out the text I don't want?
Thank you for any help you can provide.

Create index in Mongoose for array of objects

I have two models setup:
ShopsModel
var ShopsSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
var ShopsModel = mongoose.model("Shops", ShopsSchema);
FieldGroupsModel
var FieldGroupsSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
fields: [{
label: {
type: String,
required: true
},
handle: {
type: String,
required: true
}
}],
shop: {
type: mongoose.Schema.Types.ObjectId,
ref: "Shops"
}
});
var FieldGroupsModel = mongoose.model("FieldGroups", FieldGroupsSchema)
Each FieldGroups instance has a ShopsModel associated with it.
I need to create an index for the FieldGroupsModel fields[i].handle value, this index needs two rules; it needs to be unique to each FieldGroupsModel instance, so this data would be invalid:
{
title: "Some field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1"
},
{
label: "Some label 1"
handle: "some-label-1" // Error: `some-label-1` already exists as a value of `fields[i].handle`.
}
],
shop: {
"$oid": "1"
}
}
The second rule is that the first rule should only be in place for FieldGroupsModel instances which share the same shop value. So this data would be invalid:
// First bit of data
{
title: "Some field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1"
}
],
shop: {
"$oid": "1"
}
}
// Second bit of data
{
title: "Another field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1" // Error: `some-label-1` already exists as a value of `fields[i].handle` of a document which shares the same `shop` value.
}
],
shop: {
"$oid": "1"
}
}
However, this would be valid:
// First bit of data
{
title: "Some field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1"
}
],
shop: {
"$oid": "1"
}
}
// Second bit of data
{
title: "Another field group title here",
fields: [
{
label: "Some label 1"
handle: "some-label-1" // This is valid because there's no other documents with the same `shop` value with the same `fields[i].handle` value.
}
],
shop: {
"$oid": "2"
}
}
I'm quite new to Mongo and Mongoose so any help here would be greatly appreciated! :)
You call the index method on your Schema object to do that as shown here. For your case it would be something like:
FieldGroupsSchema.index({"shop": 1, "fields.handle": 1}, {unique: true});
Please read the MongoDB documentation about Compound Indexes for more detail.

Sequelize js add total count of associated models

I am trying to modify a query so it also returns a count of elements
I want to count the number of "PublicationComments" which relates to a "Publication". Right now the query looks like this:
let query = {
attributes: {
exclude: attributesToExclude,
},
where: {
'club_id': this.id,
},
order: [['date', 'DESC']],
include: [
{
model: models.PublicationComment,
association: models.Publication.hasMany(models.PublicationComment, { as: 'lastComments' }),
order: [['date', 'DESC']],
limit: 3,
include: [
{
model: models.User, as: 'user',
attributes: {
exclude: attributesToExclude,
},
}
],
},
{
model: models.PublicationLike,
association: models.Publication.hasMany(models.PublicationLike, { as: 'likes' }),
attributes: ['userId']
}
]
};
The result I am trying to obtain would look like this:
[ { id: '2',
clubId: '26',
teamId: null,
userId: '67',
date: '2017-04-18T11:23:05.628Z',
card:
{ type: 'status',
text: 'publication example text',
video: [Object] },
created_at: '2017-04-18T11:23:05.629Z',
updated_at: '2017-04-18T11:23:05.629Z',
deleted_at: null,
likes: [],
commentsCount: 4,
lastComments: [ [Object], [Object], [Object] ] }]
Note that there is a CommentCount property with the result of the wished count query
I tried doing add on include attributes the function of count by comments and repeat the association with PublicationComment model without limit parameter (I need the total).
Something like this:
attributes: {
include: [[sequelize.fn('count', sequelize.col(allComments.id), 'commentsCount']]
exclude: attributesToExclude,
},
And add the new associaton inside icludde array:
{
model: models.PublicationComment,
association: models.Publication.hasMany(models.PublicationComment, { as: 'allComments' })
}
but after two days of efforts wasted in this I am unable to make it work.
Has anyone any advise, resource or clarification that I could use to advance in this? Thanks.

UI layer pagination and sorting in extjs

I have my extjs application. As of now i am getting all my records from backend, full record set in 1 service request. I need to implement the pagination and sorting at UI level. Sorting seems be simple. How do i implement UI level pagination? Any example for this? I am getting 10-20k records so it is fine if i implement pagination at UI level? Can extjs6 handle the load?
I'd recommend you handle paging server-side. Right now you might only have 10-20k records, but what if it grows to 100k? or 1 million?
Take a look at this guide from Sencha: Grids - Paging. It explains a lot.
Good luck!
Sorting is implemented out of box. This is simple pagination example based on default ExtJs 6.2.0 application.
YourAppName.view.main.List
...
// bottom paging-bar definition. Use "tbar" for top bar, or define both.
bbar: {
xtype: 'pagingtoolbar',
displayInfo: true,
emptyMsg: 'No data to display',
items: ['->'],
prependButtons: true
}
...
items: [{
title: 'Home',
iconCls: 'fa-home',
layout: 'fit', // needed for scrolling
scrollable: true, // for scrollable items
items: [{
xtype: 'mainlist'
}]
}, {
...
YourAppName.store.Personnel
Ext.define('YourAppName.store.Personnel', {
extend: 'Ext.data.Store',
alias: 'store.banners',
autoLoad: true, // run ajax-query right after grid rendering
loadMask: true, // show preload image
pageSize: 100,
model: 'YourAppName.model.Person',
proxy: {
type: 'ajax',
url: '/personnel',
reader: {
type: 'json',
rootProperty: 'items',
totalProperty: 'total'
}
}
});
Create in app/model folder file Person.js with:
YourAppName.model.Person
Ext.define('YourAppName.model.Person', {
extend: 'Ext.data.Model',
fields: [
{ name: 'name', type: 'string', defaultValue: '' },
{ name: 'email', type: 'string', defaultValue: '' },
{ name: 'phone', type: 'string', defaultValue: '' }
]
});
As of store definition your web-server must be able to response on HTTP GET-request on URI /personnel with json like this:
{
"success": true,
"total": 20000,
"items": [
{ "name": "Jean Luc", "email": "jeanluc.picard#enterprise.com", "phone": "555-111-1111" },
{ "name": "Worf", "email": "worf.moghsson#enterprise.com", "phone": "555-222-2222" },
{ "name": "Deanna", "email": "deanna.troi#enterprise.com", "phone": "555-333-3333" },
{ "name": 'Data', "email": "mr.data#enterprise.com", "phone": "555-444-4444" }
...
]
}

JointJS: Inspector doesn't edit link label?

I'm working on a Flowchart editor and I want the ui.inspector to edit labels on links.
I did the following:
function createInspector(cellView) {
if (!inspector || inspector.options.cellView !== cellView) {
if (inspector) {
inspector.remove();
}
inspector = new joint.ui.Inspector({
inputs: {
labels:
attrs: {
text:{
text: { type: 'textarea', group: 'Labels', label: 'Label', index: 2 },
}
}
},
},
},
groups: {
labels:[ { label: 'Labels', index: 1 },
}],
cellView: cellView
});
$('#inspector-holder-create').html(inspector.render().el);
}
}
paper.on('cell:pointerdown', function(cellView) {
createInspector(cellView);
});
However, when I edit a link it shows in the JSON output:
"labels": {
"0": {
"attrs": {
"text": {
"text": "Text I entered"
}
}
}
},
but doesn't actually render on the link in the stencil.
I think the problem is with the { "0": part the inspector adds. I want to remove that and replace with it [ ] so the output will be
labels: [
{ attrs: { text: { text: 'label' } } }
]
What should I do ??
It is possible to define Inspector inputs with paths.
'labels/0/attrs/text/text': {
type: 'text',
group: 'Text',
index: 1,
label: 'Label'
}
Or as a combination of attributes nesting and paths.
'labels/0/attrs': {
text: {
text: {
type: 'text',
group: 'Text',
index: 1,
label: 'Label'
},
fontSize: {
type: 'number',
group: 'Text',
index: 2,
label: 'Font Size'
}
}
}
This is valid for Rappid v2.4.0+.
inspector = new joint.ui.Inspector({
inputs: {
'labels': [
{attrs: {
text: {
text: {
type: 'text',
group: 'someGroup',
index: 1,
label: "Label"
}
}
}}
]
}});

Resources