Populate a query in Mongoose with Schema First approach and NestJS - mongodb

First off I want to say this question is similar to this one which references this one. I have the exact same question as the second link except a notable difference. I'm trying to extend a class generated by NestJS which defines a property.
I'm using NestJs with the Schema first approach found here. I'm also generating a classes file based on my GraphQL Schema.
Here is the Schema:
type Location {
name: String!
owner: User!
}
Which generates the class:
export class Location {
name: string;
owner: User;
}
Now, I want to extend this class so I don't have to repeat the data (there are a lot more fields not shown). I also I want to add fields that live on a document but are not in the schema (_id in this example). Here is my LocationDocument and my schema.
export interface LocationDocument extends Location, Document {
_id: Types.ObjectId
}
export const LocationSchema: Schema = new Schema(
{
name: {
type: String,
required: true,
},
owner: {
type: Types.ObjectId,
ref: 'User',
}
);
Now here is my issue. The generated Location class from the GraphQL schema defines the owner property as a User type. But in reality it's a just a mongodb id until it is populated by Mongoose. So it could be a Types.ObjectId or a User on a UserDocument. So I attempted to define it as:
export interface LocationDocument extends Location, Document {
_id: Types.ObjectId
owner: User | Types.ObjectId;
}
But this throws an error in the compiler that LocationDocument incorrectly extends Location. This makes sense. Is there any way to extend the User Class but say that owner property can be a User Type (once populated by Mongoose) or a mongo object ID (as is stored in the database).

I decided that having a property that can be both types, while easy with Mongoose and JS, isn't the typed way. In my schema I have an owner which is a User type. In my database and the document which extends it, I have an OwnerId. So to people accessing the API, they don't care about the ownerId for the relationship. But in my resolver, I use the Id. One is a Mongo ID type, the other is a User type.

Related

One way one to many relation

I have a Recipe and a Tag model. Currently, the recipe contains an array of id's belonging to Tag:
#Entity()
export class Recipe extends BaseEntity {
#PrimaryGeneratedColumn('uuid')
public id!: string;
#Column({ type: 'varchar' })
public title!: string;
#Column({ type: 'varchar' })
public description!: string;
#Column({ type: 'simple-array', nullable: true })
public tags: string[];
}
#Entity()
export class Tag extends BaseEntity {
#PrimaryGeneratedColumn('uuid')
public id!: string;
#Column({ type: 'varchar' })
public name!: string;
}
However, I am currently not making use of the relational capabilities of TypeORM. I was wondering though, how would i go about doing this? Since the relation only works one way, i.e. the one Recipe having many Tags.
I could be wrong, but I believe by default, you must declare both ways--even if you only intend to use a single direction of the relationship.
For example, you need to declare that a Recipe has many Tags you also have to set up the Tag to Recipe relationship even if you aren't going to use it.
Given your example, you'll need to set up a one:many and a many:one relationship.
Since Recipe will "own" the tags, it will have the one:many:
// recipe.entity.ts
#OneToMany(() => Tag, (tag) => tag.recipe)
tags: Tag[];
Then the inverse will look like this:
// tag.entity.ts
#ManyToOne(() => Recipe, (recipe) => recipe.tags)
#JoinColumn({
name: 'recipeId',
})
recipe: Recipe;
If you're considering having many recipes own the same tag, you may need to consider using a many:many relationship
EDIT
I suppose you could technically store an array of id's in a column to represent tags for any given recipe. The question here is, what happens if you decide you need further info on any given tag?
IMO, (and it's just that so take all of this with a grain of salt). You are bending your recipe table to also store relationship info.
I have found it to be more helpful to keep my "buckets" (tables) as specific as possible. That'd leave us with:
recipes | tags | recipes_tags
-----------------------------
That way my recipes table just has recipes & that's it. "Just give me all recipes...". Tags is the same, "just show me all tags"
The two things are completely different entities. By setting up a ManyToMany relationship, we're telling TypeORM that these two columns are related--without "muddying" either of their underlying data.
You can add/remove columns on the pivot table should you decide you want more info about the relationship. At that point, you'd still be working with the relationship, not a tag or recipe so your data would still be nice & lean!
Another example from one of my own use cases...
I have an Activity and a Resource any given resource can have one or more Activities. (activities = tags/ resources = recipes)
// activity.entity.ts
...
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
...
#ManyToMany((type) => Resource, (resource) => resource.activities)
resources: Resource[];
// resource.entity.ts
#PrimaryGeneratedColumn('uuid')
id: string;
#Column()
name: string;
...
#JoinTable()
#ManyToMany((type) => Activity, (activity) => activity.resources)
activities: Activity[];
The above generates a resources_activities_activities table.
Within that table is:
resourceId | activityId
------------------------
I could add additional columns here as well. createdBy or status or something else that is specific to the relationship. Each entry in this table has a relationship back to the activity and the resource--which is great!
I realize we've gone outside the scope of your original question, but I think this is a pretty small step outside, for a potential big win later on.
When I make a request to get a resource: example.com/resources/123 I get something like this back:
"id": "123"
...
"activities": [
{
"id": "f79ce066-75ba-43bb-bf17-9e60efa65e25",
"name": "Foo",
"description": "This is what Foo is.",
"createdAt": "xxxx-xx-xxxxx:xx:xx.xxx",
"updatedAt": "xxxx-xx-xxxxx:xx:xx.xxx"
}
]
...
Likewise, any time I get an activity, I also get back any resources that are related to it. In my front-end I can then easily do something like resource.activities.

TypeORM - postgresSQL / saving data in the DB

So, i'm new into this typeORM thing, and actually also new into postgresSQL DB, and there's something i couldn't undertand about typeORM and making relations between tables.
My Question: So, i have two entities, User and Post. When you create a post, we store the user ( creator of the post ) in the DB using #JoinColumn, and when i go to users table, i can see the name of that field (username), but, inside User entity, we have an array of Posts, but, that field doesn't appear in the postgres DB, so, when i create a relation, #ManyToOne and #OneToMany, what data stores in the DB and which don't ? Besides that, when i fetch stuff, i can fetch the array, but, does that array is store in the DB or what ? I'm kinda confused with this, so, now let me show you the code
User entity
import {
Entity as TOEntity,
Column,
Index,
BeforeInsert,
OneToMany
} from "typeorm";
import bcrypt from "bcrypt";
import { IsEmail, Length } from "class-validator";
import { Exclude } from "class-transformer";
import Entity from "./Entity";
import Post from "./Post";
#TOEntity("users")
export default class User extends Entity {
constructor(user: Partial<User>) {
super();
Object.assign(this, user);
}
#Index()
#IsEmail(undefined, { message: "Must be a valid email address" })
#Length(5, 255, { message: "Email is empty" })
#Column({ unique: true })
email: string;
#Index()
#Length(3, 200, { message: "Must be at leat 3 characters long" })
#Column({ unique: true })
username: string;
#Exclude()
#Length(6, 200, { message: "Must be at leat 3 characters long" })
#Column()
password: string;
#OneToMany(() => Post, post => post.user)
posts: Post[];
#BeforeInsert()
async hashedPassword() {
this.password = await bcrypt.hash(this.password, 6);
}
}
Post entity
import {
Entity as TOEntity,
Column,
Index,
BeforeInsert,
ManyToOne,
JoinColumn,
OneToMany
} from "typeorm";
import Entity from "./Entity";
import User from "./User";
import { makeid, slugify } from "../util/helpers";
import Sub from "./Sub";
import Comment from "./Comment";
#TOEntity("posts")
export default class Post extends Entity {
constructor(post: Partial<Post>) {
super();
Object.assign(this, post);
}
#Index()
#Column()
identifier: string; // 7 Character Id
#Column()
title: string;
#Index()
#Column()
slug: string;
#Column({ nullable: true, type: "text" })
body: string;
#Column()
subName: string;
#ManyToOne(() => User, user => user.posts)
#JoinColumn({ name: "username", referencedColumnName: "username" })
user: User;
#ManyToOne(() => Sub, sub => sub.posts)
#JoinColumn({ name: "subName", referencedColumnName: "name" })
sub: Sub;
#OneToMany(() => Comment, comment => comment.post)
comments: Comment[];
#BeforeInsert()
makeIdAndSlug() {
this.identifier = makeid(7);
this.slug = slugify(this.title);
}
}
How the User entity looks as a table in the DB
So, as you can see, there's no field with name posts ( which is weird, because as i already said, if i can fetch that, where is that data if i can't see it in the DB )
Now, let me show you Post entity
What i want to understand: So, we have the relationship between tables, know, i tried to search stuff in order to understand that, but i couldn't find anything, so, if you can help me with this mess, i would really aprecciate that, so, thanks for your time !
Let's take this section and try to understand piece by piece:
#ManyToOne(() => User, user => user.posts)
#JoinColumn({ name: "username", referencedColumnName: "username" })
user: User;
1. #ManyToOne(() => User, user => user.posts):
#ManyToOne: This annotation tells typeORM that Post entity is going to have a many to one relationship. From the postgres DB point of view, this means that posts table is going to have a new column (foreign key) which points to a record in some other table.
() => User: This is called definition of the target relationship. This helps typeORM to understand that the target of the relationship is User entity. For postgres DB, this means the foreign key in posts table is going to reference a row in users database
user => user.posts: This is called the inverse relationship. This tells typeORM that the related property for the relationship in User entity is posts. From the postgres DB point of view, this has no meaning. As long as it has the foreign key reference, it can keep the relationship between the two tables.
2. #JoinColumn({ name: "username", referencedColumnName: "username" }):
#JoinColumn: In this scenario, this annotation helps typeORM to understand the name of the foreign key column in posts table and the name of the referenced column in users table
name: "username": This is the name of the column in posts table which is going to uniquely identify a record in users table
referencedColumnName: "username": This is the name of the column in users table which is going to be referenced by the foreign key username in posts table.
inside User entity, we have an array of Posts, but, that field doesn't appear in the postgres DB
The array of Posts is there for the typeORM to return you an array of linked posts. It is not needed by postgres DB to contain the relationship.
when i create a relation, #ManyToOne and #OneToMany, what data stores in the DB and which don't
Whatever property you decorated using #Column will be there in the table as it is. And for the relationships, only the foreign key will be saved. As an example, when you save a Post entity, it will save only the relevant columns in that entity + username foreign key.
when i fetch stuff, i can fetch the array, but, does that array is store in the DB or what ?
When you query User entity, typeorm uses the annotations to join users table with posts table and return you the posts with the user you searched. But in database, it saves users and posts data in their respective tables and uses username foreign key to keep the relationship between them.
I hope this helps you to understand what happens. Cheers 🍻 !!!

AWS Amplify and GraphQL Interfaces

How would you deal with interfaces and using them for connections in a data model using the AWS Amplify Model Transforms?
interface User #model {
id: ID
email: String
created: AWSTimestamp
}
type ActiveUser implements User {
id: ID
first: String
last: String
email: String
created: AWSTimestamp
}
type InvitedUser implements User {
id: ID
email: String
created: AWSTimestamp
invitedBy: String
}
type Team #model {
users: [User] #connection
}
It seems like my choices are to put #model on the types but then I get separate Dynamo tables and queries on the Query once amplify update api is run.
Can the transformer support interfaces as documented here: https://docs.aws.amazon.com/appsync/latest/devguide/interfaces-and-unions.html
I also found some support tickets, but was wondering if there was anything out there that enabled this feature. Here are the support tickets I found:
https://github.com/aws-amplify/amplify-cli/issues/1037
https://github.com/aws-amplify/amplify-cli/issues/202
You only use #connection to link two databases together (which must be made from type and not interface), so if you don't want to do that then just get rid of the #connection and the Team database will simply have users be of type [User]. I am not entirely what you want to do but I would do something like:
type User #model {
id: ID
first: String!
last: String!
email: String!
created: AWSTimestamp
isActive: boolean
invitedBy: String
team: Team #connection(name: "UserTeamLink")
}
type Team #model {
users: [User!] #connection(name: "UserTeamLink")
}
Where the fields first, last, and email are required when creating a new user, and you can distinguish between an active user with a boolean, and when you query the User database it returns the Team item from the Team database as well (I am guessing you want other fields like team name, etc.?), so when you create a Team object you pass in the teamUserId (not shown below but created when using amplify) that will allow you to attach a newly created Team to an existing user or group of users.
I think you could keep the common fields in User, and extra info in separate type. Not sure if this is the best practice, but it should work for this scenario
enum UserType {
ACTIVE
INVITED
}
type User #model #key(name:"byTeam", fields:["teamID"]){
id: ID!
teamID: ID!
email: String
created: AWSTimestamp
type: UserType
activeUserInfo: ActiveUserInfo #connection(fields:["id"])
invitedUserInfo: InvitedUserInfo #connection(fields:["id"])
}
type ActiveUserInfo #key(fields:["userID"]){
userID: ID!
first: String
last: String
}
type InvitedUserInfo #key(fields:["userID"]){
userID: ID!
invitedBy: String
}
type Team #model {
id:ID!
users: [User!] #connection(keyName:"byTeam", fields:["id"])
}

Resolving auto-generated typescript-mongodb types for GraphQL output

I'm using the typescript-mongodb plugin to graphql-codegen to generate Typescript types for pulling data from MongoDB and outputting it via GraphQL on Node.
My input GraphQL schema looks like this
type User #entity{
id: ID #id,
firstName: String #column #map(path: "first_name"),
...
The generated output Typescript types look correct
export type User = {
__typename?: 'User',
id?: Maybe<Scalars['ID']>,
firstName?: Maybe<Scalars['String']>,
...
And the corresponding DB object
export type UserDbObject = {
_id?: Maybe<String>,
first_name: Maybe<string>,
...
The problem is when actually sending back the mongo document as a UserDbObject I do not get the fields mapped in the output. I could write a custom resolver that re-maps the fields back to the User type, but that would mean I'm mapping the fields in two different places.
i.e. I do not get mapped fields from a resolver like this
userById: async(_root: any, args: QueryUserByIdArgs, _context: any) : Promise<UserDbObject> => {
const result = await connectDb().then((db) => {
return db.collection<UserDbObject>('users').findOne({'_id': args.id}).then((doc) => {
return doc;
});
})
...
return result as UserDbObject;
}
};
Is there a way to use the typescript-mongodb plugin to only have to map these fields in the schema, then use the auto-generated code to resolve them?
You can use mappers feature of codegen to map between your GraphQL types and your models types.
See:
https://graphql-code-generator.com/docs/plugins/typescript-resolvers#mappers---overwrite-parents-and-resolved-values
https://graphql-code-generator.com/docs/plugins/typescript-resolvers#mappers-object
Since all codegen plugins are independent and not linked together, you should do it manually, something like:
config:
mappers:
User: UserDbObject
This will make typescript-resolvers plugin to use UserDbObject at any time (as parent value, or as return value).
If you wish to automate this, you can either use the codegen programmatically (https://graphql-code-generator.com/docs/getting-started/programmatic-usage), or you can also create a .js file instead of .yaml file that will create the config section according to your needs.

Sails.js and pluralized relational database table names

How do I configure Sails.js / Waterline to default to pluralized relational database table names that correspond to singular models (same as Rails)?
(E.g. A model called 'Person' should default to a PostgreSQL table called 'people'.)
Just add the tableName: 'people' property to the model:
// Person.js
module.exports = {
tableName: 'people',
attributes: {
id: 'integer',
name: 'string'
}
};
There does not appear to be a global setting in Sails.js that pluralizes database table names automatically for models with singular names.
You can put this in your blueprints.js or local.js file:
blueprints: { // if in your local.js wrap in this object
pluralize: true
}
It won't get it right every time, so the tableName property is still useful for odd cases, but for most pluralized terms it will work.