Sails.js - Waterline Model - Association to itself - mysql

I want to create a Tree like storage structure to be used with my app, but can't find enough documentation on how to create a tree model using Waterline attributes.
Case is simple. I do need to have a set of folders, that can have multiple levels of subfolders and in the end, files. What you usually do in mySQL for this kind of data is to add a parent_id field to your model as a foreign key to the model itself.
How can this be done using attributes in sailsjs/waterline model?
I've tried doing something like the following, which generates quite a bit of redundant and orphaned data:
--
attributes: {
name: {
type: 'string'
},
parentFolder: {
model: 'Folder'
},
childFolders: {
model: 'Folder',
via: 'parentItem'
}
}
--
Any ideas?
And by the way, if this is possible, let's say for example using mySQL as a backend. How will it replicate to say, mongoDB?

This seemed to work:
name: {
type: 'string',
maxLength: 255,
required: true
},
parent: {
model: 'folder'
},
childs: {
collection: 'folder',
via: 'parent'
}
I do believe duplicates were being generated by posting data directly via GET in the browser. I'm posting data with a client via POST and it seems to work as expected. (At least from what I see in mySQL)

Related

Monaco editor default json uri schema

I'm using monaco editor to edit JSON and I would like to set a custom diagnostic option.
I'm trying that https://microsoft.github.io/monaco-editor/playground.html#extending-language-services-configure-json-defaults
// Configures two JSON schemas, with references.
var jsonCode = [
'{',
' "p1": "v3",',
' "p2": false',
"}"
].join('\n');
var modelUri = monaco.Uri.parse("a://b/foo.json"); // a made up unique URI for our model
var model = monaco.editor.createModel(jsonCode, "json", modelUri);
// configure the JSON language support with schemas and schema associations
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
validate: true,
schemas: [{
uri: "http://myserver/foo-schema.json", // id of the first schema
fileMatch: [modelUri.toString()], // associate with our model
schema: {
type: "object",
properties: {
p1: {
enum: ["v1", "v2"]
},
p2: {
$ref: "http://myserver/bar-schema.json" // reference the second schema
}
}
}
}, {
uri: "http://myserver/bar-schema.json", // id of the second schema
schema: {
type: "object",
properties: {
q1: {
enum: ["x1", "x2"]
}
}
}
}]
});
monaco.editor.create(document.getElementById("container"), {
model: model
});
Where does uri: "http://myserver/foo-schema.json" come from ? I just want to use default JSON schema. Not my own.
Setting uri like this works :
uri: "http://localhost:4200/assets/monaco-editor/min/vs/language/json/jsonMode.js",
But is there a clean way to set this value ? Maybe uri value for JSON is available somewhere ? I searched through monaco.languages.json.jsonDefaults but I did not find anything.
"http://myserver/foo-schema.json" is an arbitrary value-- you can make it anything you want. It only matters if you are also using enableSchemaRequest-- in which case it should point to the location that you want the schema to be fetched from-- but you're not doing that, so that doesn't matter. In fact, everything related to this URI is irrelevant to what you are trying to do, if I'm understanding your intent correctly.
When you say "I just want to use default JSON Schema, Not my own", I think what you mean to say is that you just want to ensure that it is valid JSON, right? Because, there is no such thing as "default JSON Schema"-- by definition, it is defined by you-- but there is such a thing as a formal definition of what JSON is (JSON Schema, on the other hand, assumes that you are already starting with valid JSON, and allows you to then define a schema that your (valid) JSON must conform to).
Assuming you just want to ensure it is valid JSON (but you don't care that the json conform to some custom schema), setting the language to 'json' is all you need to do and your code can be as simple as:
var myBadJSONText = '{this is not : "JSON"}'
monaco.editor.create(document.getElementById('container'), {
language: 'json',
value: myBadJSONText
});
which running in the Monaco playground gives you:

(electron-store) How can I use "patternProperties" when define schema

I am using library for my electron app called electron-store
It has a feature to validate config data.
I want the value to be stored in config file is a string. I can achive that by define schema like this:
const schema = {
1: {
type: 'string',
},
2: {
type: 'string',
},
3: {
type: 'string',
},
4: {
type: 'string',
},
};
const store = new Store({schema});
The data in my config.json file:
{
"1": "lorem epsum...",
"2": "epsum lorem...",
"3": "epsum epsum...",
"4": "lorem lorem..."
}
The problem is I have hundreds line of datas like that, so it would be great if I could just define:
const schema = {
[any_key_name]: {
type: 'string',
},
};
I think I can use "patternProperties" when defining schema to achive it but I don't know how. help me please.
It looks like you cannot do this with electron-store as you want.
The docs say the following:
You should define your schema as an object where each key is the name
of your data's property and each value is a JSON schema used to
validate that property.
https://github.com/sindresorhus/electron-store#schema
This means that the root "schema" is not a JSON Schema. Only the value of each KEY is a JSON Schema.
If you want to use dynamic names, I think you would need to nest it under a specific key name, and validate that as a single object, although this is probably not what you really want to do with a store.
Sorry, I'm not familiar with electron-store specifically.
If you COULD provide a full JSON Schema for the whole store...
You can use patternProperties.
If you don't need to check the key follows any specific regex, you can use additionalProperties, which would then cover all properties not checked by properties (if present).
LEt's look at the specification: https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.5.6
The value of "additionalProperties" MUST be a valid JSON Schema.
This keyword determines how child instances validate for objects,
and does not directly validate the immediate instance itself.
Validation with "additionalProperties" applies only to the child
values of instance names that do not match any names in "properties",
and do not match any regular expression in "patternProperties".
As a pure JSON Schema, you'd be looking at...
{
"additionalProperties": {
"type": "string"
}
}
You can easily test this using https://jsonschema.dev (link has an example for you)

how to update mongo document without knowing what has been modified

I need a more or less very general advice how to update my DB.
I have a huge JSON (ugly doubly nested) data coming from the client and what's worse is that I do not know which particular one has been modified, which means I can't use { $set: something ..
I desinged referenced documents in order to avoid doubly nested array.
Therefore I have 5 collections.
locations
floors
stores
restrooms
benches
e.g.
location has floors
floor has stores, restrooms, and benches and so on.
here is my simplified schema
const Location = new Schema({
floors: [{
type: Schema.Types.ObjectId,
ref: 'FloorSchema',
}],
});
const FloorSchema = new Schema({
stores: [{
type: Schema.Types.ObjectId,
ref: 'StoreSchema',
}],
restrooms: [{
type: Schema.Types.ObjectId,
ref: 'RestroomSchema',
}],
benches: [{
type: Schema.Types.ObjectId,
ref: 'BenchSchema',
}],
});
From the client side, there is no api request until the changes are done.
So the first request I get from the client is huge map data with no history recorded.
Do you think it is a reasonable idea to drop the entire collections (except the location collection) and save a whole new map data instead of investigating what has been modified?
Thank you,
======
I found one question&answer which seems to be very relevant.
I will try the first solution

No exception upon insertion of document

I am learning MongoDB. The thing that is confusing me right now is collections don't enforce the strict structure like RDBMS. I created a document with following parameters:
db.tempTable.insert({
id: 1,
name: umer
});
then I inserted:
db.tempTable.insert({
"id":2,
"name": "khan",
"yolo":"todolo"
});
Both the queries were successful. I thought Mongo would raise an exception in the second insertion because the collection didn;t have the "YOLO" column in the collection.
Why is that? Can we enforce the strict structure to avoid confusions while inserting in the table?
Best
No, MongoDB is schemaless. This means there is no strict schema. The only way you can raise an exception to ensure all documents have the same fields is at your code level, perhaps by using ORM
Like #hd says, mongodb is schemaless. But there is solutions to play with like validators that allow you to validate data before to insert them.
#example of new validator
db.runCommand( {
collMod: "contacts",
validator: { $or: [ { phone: { $exists: true } }, { email: { $exists: true } } ] },
validationLevel: "moderate"
} )

How to set the `type` property of the serialized JSON object in Ember

I have a model named line-item in my ember application. When I try to create a line-item record, I observe in the network tab that ember serialises a JSON object that looks like so:
{
data: {
quantity: 1,
type: "lineItems", // note this
links: {
cart: {linkage: {id: "7", type: "carts"}}
product: {linkage: {id: "a65874aa87b", type: "products"}}
}
}
}
What I would like to do is change the value of the type property to line-items instead (since the backend expects that). I have tried overriding the serializeIntoHash and typeForRoot methods of the RESTSerializer class, but no luck there. I'm probably mucking around with the wrong methods, but I'm just not sure where I should be looking at instead.
I would really appreciate some pointers in the right direction.Thanks!