Skip to content

Creating relations

Adam Juhos edited this page Jan 14, 2019 · 5 revisions

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).

1. Create your second edge

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
        }
    }
)

2. Update your first edge

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.

3. Create the relation

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
    }
}

4. Relation specific operations

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.

Clone this wiki locally