-
Notifications
You must be signed in to change notification settings - Fork 3
Creating relations
Relations are connections between models, or to be exact, between a model field and a model. So, you need two edges to create a relation (or at least, this is the easy way).
A relation needs two edges, so first you have to create a second edge:
const { MongooseModelFactory } = require("api-model-mongoose")
module.exports = MongooseModelFactory.createModel("user", "users",
{
name: {
type: String,
required: true,
unique: true
}
}
)And you have to update your first edge:
const { MongooseModelFactory } = require("api-model-mongoose")
const mongoose = require("mongoose"),
ObjectId = mongoose.Schema.Types.ObjectId
module.exports = MongooseModelFactory.createModel("entry", "entries",
{
name: {
type: String,
required: true,
unique: true
},
value: {
type: String,
required: true
},
owner: {
type: ObjectId,
ref: 'user'
}
}
)Now every entry has an owner, which is a user entry.
As the Mongoose Model Provider can detect relations automatically, you don't need to do anything, your relation will just work! :)
For advanced cases, you can read more here.
If the detected and auto-generated relation has to be modified, you can provide the relation modifier for the field type in the schema:
owner: {
type: ObjectId,
ref: 'user',
relation: {
type: 'many-to-one', // 'one-to-one'|'many-to-many'|'many-to-one'
foreignName: 'entries' // The name of the relation on the other side
}
}Once you have a relation, your edges automatically provide the following related operation:
- Read related entry or entries: Returns the value on the other side of the relation for a specific entry.
- Embed related entry or entries: Populates the value on the other side of the relation for a specific entry or a list of entries.
- Create/update/delete related entry
That's it, now you have an API with two edges and one relation. Now you should provide it for consumption.
Getting started
• 1. Creating the API
• 2. Creating edges
• 3. Creating relations
• 4. Providing the API
• 5. Consuming the API
API Composition
• Edges
• Relations
• Actions, operations
• Custom methods
Providers
• Model providers
• Access providers
• API provider
API Consumption
• Low-level access
• High level access
• Swagger support