Skip to main content
Version: v2.x.x

One to Many (Inverse) / Belongs To

One to Many (Inverse) / Belongs To

Belongs To

Now that we can access all of a post's comments, let's define a relationship to allow a comment to access its parent post. To define the inverse of a hasMany relationship, define a relationship method on the child model which calls the belongsTo method:

import { Mongoloquent } from "mongoloquent";
import Post from "./yourPath/Post";

class Comment extends Mongoloquent {
static collection = "comments";

static post() {
return this.belongsTo(Post, "postId", "_id");
}
}

Once the relationship has been defined, we can retrieve a comment's parent post by accessing the post "dynamic relationship property":

import Comment from "./yourPath/Comment";

const comment = await Comment.with("post").find("50ab7e3d05d58a1ad246aa87");

// your relationship data can accessed in the data property
console.log(comment.data);

Monggoloquent can also select or exclude certain related model keys

import Comment from "./yourPath/Comment";

// with select keys
await Comment.with("post", {
select: ["title"],
}).find("50ab7e3d05d58a1ad246aa87");

// with exclude keys
await Comment.with("comments", {
exclude: ["title"],
}).find("50ab7e3d05d58a1ad246aa87");

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

_

Partners