Sequelize: How to return relationships as JSON attribute? - json

I have a simple database of articles and authors.
Each article is connected to author(s) through a belongsToMany relationship, for example:
Articles
id: 1
title: Test
Authors
id: 1
name: Foo
id: 2
name: Bar
Say, for example, that the article is joined to both authors.
Using sequelize, how can I have Articles.findAll() return the authors along with its details, for example:
"articles": [
{
"id": 1,
"title": "Test",
"author_ids": "[1,2]"
}
]

Use the include option in your query:
Articles.findAll({
include: [Author]
}).then(function(articles) {
console.log(articles[0].authors[0].author_id);
});

Related

Fetch users data with related clients data in Yiii2 api

I need to get an API response, where each client row has its associated users' data in it. like this:
clients: [
{
id: 1
name: 'client_1',
users: [{ id: 1, name: 'user_1', clients_id: 1}, { id: 2, name: 'user_2',
clients_id: 1 }],
},
{
id: 2
name: 'client_2',
users: [{ id: 3, name: 'user_3', clients_id: 2}, { id: 4, name: 'user_4',
clients_id: 2 }],
},
]
How can I write Yii2 code for this result? Do query builder works here or do I need to use MySQL syntax?
I believe you have two tables those are related some how. You can achieve it by defining client relation in users table. One you defined the relation define extrafields function and add the relation there.
In url use expand query param and mention your relation there.
You are done!
Sample URLhttp://localhost/users?fields=id,email&expand=profile
Check the documentation

Couchbase N1QL query to get id of documents connected as a linked list

I have collection that contain documents with the following structure
{
id: "doc01",
property1: "",
nextCollection: "doc02"
prevCollection: null
},
{
id: "doc02",
property1: "",
nextCollection: "doc03",
prevCollection: "doc01"
},
{
id: "doc03",
property1: "",
nextCollection: null,
prevCollection: "doc02"
},
The above code contains three documents. What I want to do is to write a N1QL query that gets all documents in the list given doc01 id.
That is I want the return type to be
[
{
id: "doc01",
property1: "",
nextCollection: "doc02"
prevCollection: null
},
{
id: "doc02",
property1: "",
nextCollection: "doc03",
prevCollection: "doc01"
},
{
id: "doc03",
property1: "",
nextCollection: null,
prevCollection: "doc02"
}
]
How to write such query?
N1QL doesn't support hierarchical queries or recursive CTE.
Instead of single N1QL statement you can achieve this with the following options
Using N1QL UDF checkout https://www.couchbase.com/blog/traverse-hierarchy-user-defined-functions-in-7-1/
From application using SDK (As you know document keys you can use collection.get() avoid N1QL all together). You can even stop when recursive list detected circular and if list is huge control how many you want in the list.
Get the first document and add to the list
In loop until nextDocument is known value
get the document of key nextDocument
add to the list

How can i make a mongoDB subdocument have an unique id or incremented id?

Solved
I am having this MongoDB document:
{
_id: "5e3bf72db5074c1e205409f5",
todos: [
{
title: "title",
description: "description",
state: "state",
priority: "priority"
}
],
title: "test project"
}
and I want to keep the main '_id:' property for the project but also add an "_id:" or something of that sorts to my todos so that I can do CRUD operations on them alone easier. Is there a way of making a unique id or autoincremented id for them? The final result would look like this
Is there a way to do this? also, any other suggestions are appreciated.
{
_id: another unique id or autoincrement key,
title: "title",
description: "description",
state: "state",
priority: "priority"
}

Schema validation, how to enforce the existance of property at top level based on condition in lower level

I'm trying to write a schema to validate a yaml file after parsing it into JSON.
Supposing that this is my .yml file with 2 top level properties, cars and garage.
cars is optional while garage is required.
However, one of garage's sub-properties is cars. If cars under garage is defined, I want the schema to make sure that cars at the top level is also defined. Otherwise, the schema is not going to be valid
cars:
- BMW
- Mercedes-Benz
- Audi
garage:
location: Miami
cars:
- BMW
- Audi
My Schema:
{
properties: {
cars: {
type: 'array',
items: {
type: 'string'
}
},
garage: {
type: 'object',
properties: {
location: {
type: 'string'
},
cars: {
type: 'array'
}
},
required: ['garage']
}}
So I tried doing an if-else at the top level
{
if: { properties: { garage: { cars: {type: 'array'}}}},
then: {required:['cars']},
properties: {
cars: {
type: 'array',
items: {
type: 'string'
}
},
garage: {
type: 'object',
properties: {
location: {
type: 'string'
},
cars: {
type: 'array'
}
},
required: ['garage']
}}
But it seems that I'm doing it wrong or it doesn't serve that purpose.
Also doing anyOf at the top level to match sub-schemas didn't work for me..
Any help ?
You can specify the referential integrity constraint (together with all the other requirements) using the "JSON Extended Structure Schema" language, JESS.
Here is the complete JESS schema presented as a single JSON document:
[ "&",
["&",
{"::>=": {"garage": {"location": "string", "cars": [ "string" ] } } }
],
{"ifcond": { "has": "cars" },
"then": ["&", { "forall": ".[cars]", "schema": ["string"] } ]
},
{"setof": ".[garage]|.[cars][]", "subsetof": ".[cars][]"}
]
The first "&" introduces the conjunction of the three requirements, the last of which is the referential integrity constraint.
The JESS repository has a schema conformance checker, which I used to verify your sample (expressed as JSON) against the above schema.
The value of if must be a JSON Schema.
If you take the value of if as a JSON Schema on it's own and test the validation result of applying it to the correct location in your JSON instance, it may help you debug this type of issue.
In your if block, you need to put nest cars under properties, just like you've done in your main schema.
You may also want to make both garage and cars required in your if block.]
You cannot however define that you want the values from garage.cars to be included in your cars array.

REST api design to retrieve summary information

I have a scenario in which I have REST API which manages a Resource which we will call Group.
A Group is similar in concept to a discussion forum in Google Groups.
Now I have two GET access method which I believe needs separate representations.
The 1st GET access method retrieves the minimal amount of information about a Group.
Given a group_id it should return a minimal amount of information like
{
group_id: "5t7yu8i9io0op",
group_name: "Android Developers",
is_moderated: true,
number_of_users: 34,
new_messages: 5,
icon: "http://boo.com/pic.png"
}
The 2nd GET access method retrives summary information which are more statistical in nature like:
{
group_id: "5t7yu8i9io0op",
top_ranking_users: {
[ { user: "george", posts: 789, rank: 1 },
{ user: "joel", posts: 560, rank: 2 } ...]
},
popular_topics: {
[ ... ]
}
}
I want to separate these data access methods and I'm currently planning on this design:
GET /group/:group_id/
GET /group/:group_id/stat
Only the latter will return the statistical information about the group. What do you think about this ?
I don't see a problem with your approach. Since the statistics are basically separate data, you could treat the stats as a separate resource, too, providing a URI like
GET /stat/:group_id
Additionally you can cross reference your resources (meaning a group links to the corresponding stat resource and vice versa):
GET /group/5t7yu8i9io0op
{
group_id: "5t7yu8i9io0op",
group_name: "Android Developers",
is_moderated: true,
number_of_users: 34,
new_messages: 5,
icon: "http://boo.com/pic.png",
stats: "http://mydomain.com/stat/5t7yu8i9io0op"
}
GET /stat/5t7yu8i9io0op
{
group: "http://mydomain.com/group/5t7yu8i9io0op",
top_ranking_users: {
[ { user: "george", posts: 789, rank: 1 },
{ user: "joel", posts: 560, rank: 2 } ...]
},
popular_topics: {
[ ... ]
}
}
What would be even better would be if you embedded the link to the statistics in the group summary:
{
group_id: "5t7yu8i9io0op",
group_name: "Android Developers",
is_moderated: true,
number_of_users: 34,
new_messages: 5,
icon: "http://boo.com/pic.png"
stats_link : "http://whatever.who/cares"
}