Has Many Through
One to Many Relationships
One to Many
The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform. A Project
model might access many Deployment
models through an intermediate Environment
model. Using this example, you could easily gather all deployments for a given project. Let's look at the collections required to define this relationship:
projects
_id - ObjectId
name - string
environments
_id - ObjectId
projectId - ObjectId
name - string
deployments
_id - ObjectId
environmentId - ObjectId
commitHash - string
Now that we have examined the collection structure for the relationship, let's define the relationship on the Project
model:
import { Mongoloquent } from "mongoloquent";
import Environment from "./yourPath/Environment";
import Deployment from "./yourPath/Deployment";
class Project extends Mongoloquent {
static collection = "projects";
static deployments() {
return this.hasManyThrough(
Deployment,
Environment,
"projectId",
"environmentId"
);
}
}
The first argument passed to the hasManyThrough method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.
import Project from "./yourPath/Project";
const project = await Project.with("deployments").find(
"65ab7e3d05d58a1ad246ee87"
);
// your relationship data can accessed in the data property
console.log(project.data);
Select and Exclude Related Model Keys
Monggoloquent can also select
or exclude
certain related model keys
import Project from "./yourPath/Project";
// with select keys
await Project.with("deployments", {
select: ["commitHash"],
}).find("65ab7e3d05d58a1ad246ee87");
// with exclude keys
await Project.with("deployments", {
exclude: ["commitHash"],
}).find("65ab7e3d05d58a1ad246ee87");
Support us
Mongoloquent is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here.
Sponsors
_