Possibility to have sub-documents by reference?
Opened this issue · 3 comments
Deleted user commented
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 commented
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.
Deleted user commented
I'll try to use your class and see what I get.
Deleted user commented
@vadimdemedes if it is already on the roadmap we could reference this on the roadmap and close this issue.