Skip to content
This repository has been archived by the owner on Feb 10, 2022. It is now read-only.

Possibility to have sub-documents by reference? #161

Open
ghost opened this issue Jan 31, 2017 · 3 comments
Open

Possibility to have sub-documents by reference? #161

ghost opened this issue Jan 31, 2017 · 3 comments

Comments

@ghost
Copy link

ghost commented Jan 31, 2017

I have the models below:

import { Model } from 'mongorito';

export class User extends Model {
  configure () {
    this.before('create', 'checkIfExists');
  }
  async checkIfExists () {
    let exists = true;
    await User.find({ name: this.get('name') })
    .then(res => exists = !!res.length);
    if (exists) throw new Error('User already exists on the database');
  }
}

export class Character extends Model {
  async configure () {
    await User.findOne({ _id: this.get('owner') })
    .then(res => this.set('owner', res));
    this.before('create', 'checkIfExists');
  }
  async checkIfExists () {
    let exists = true;
    await Character.find({ owner: this.get('owner') })
    .then(res => exists = !!res.length);
    if (exists) throw new Error('Character already exists on the database');
  }
}

and want to save documents like this:

const char = new Character({
  name: "Tobias",
  owner: "587fab63213d494a6b865547" // an ID for an existing User on DB
});

Am I getting something wrong here?
I didn't understood how to get the Mode.populate() thing to work with this models neither.

@EdenCoder
Copy link
Contributor

I did something similar in https://github.com/eden-js/eden/blob/master/lib/core/model.js

Basically instead of doing .get ('field') you'd do await char.model ('owner'),

The major issue is the need to register all models beforehand, else mongorito has no idea which class the sub-document references. However I think @vadimdemedes has added this to the roadmap.

@ghost
Copy link
Author

ghost commented Feb 1, 2017

I'll try to use your class and see what I get.

@ghost
Copy link
Author

ghost commented Feb 1, 2017

@vadimdemedes if it is already on the roadmap we could reference this on the roadmap and close this issue.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant