One to Many
One to Many Relationship
One to Many
A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models. For example, a blog post
may have an infinite number of comments
. Like all other Mongoloquent
relationships, one-to-many relationships are defined by defining a method on your Mongoloquent
model.
import { Mongoloquent } from "mongoloquent";
import Comment from "./yourPath/Comment";
class Post extends Mongoloquent {
static collection = "posts";
static comments() {
return this.hasMany(Comment, "postId", "_id");
}
}
Once the relationship method has been defined, we can access the collection
of related comments by accessing the comments
property in the data property.
import Post from "./yourPath/Post";
const post = await Post.with("comments").find("65ab7e3d05d58a1ad246ee87");
// your relationship data can accessed in the data property
console.log(post.data);
Select and Exclude Related Model Keys
Monggoloquent can also select
or exclude
certain related model keys
import Post from "./yourPath/Post";
// with select keys
await Post.with("comments", {
select: ["text"],
}).find("65ab7e3d05d58a1ad246ee87");
// with exclude keys
await Post.with("comments", {
exclude: ["text"],
}).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
_