0

I can not post data json with relation object.

I use mongoDB.
I have 3 table: table_1, table_2, table_3.

I create relation EmbedsMany and EmbedsOne:
- table_2 EmbedsOne table_1.
- table_2 EmbedsMany table_3.

I don't know create post data json to create a new item of table_2 with item of table_1.

import { ..., embedsMany, embedsOne } from '@loopback/repository';
import { Model1, Mode1WithRelations } from './model-1.model';
import { Model3, Model3WithRelations } from './model-2.model';
@model({
    settings: {
        strictObjectIDCoercion: true,
        mongodb: {
            collection: 'table_2'
        }
    }
})
export class Model2 extends Entity {
    @property({
        type: 'string',
        id: true,
        mongodb: {
            dataType: 'ObjectID' // or perhaps 'objectid'?
        }
    })
    id?: string;

    @embedsMany(() => Model3)
    model3?: Model3[];

    @embedsOne(() => Model1)
    model1: Model1;
}

export interface Model2Relations {
    // describe navigational properties here
    model3?: Model3WithRelations[];
    model1: Mode1WithRelations;
}

export type Model2WithRelations = Model2 & Model2Relations;

Repository model 2

import { DefaultCrudRepository } from '@loopback/repository';
import { Model2, Model2Relations } from '../models';
import { DbDataSource } from '../datasources';
import { inject } from '@loopback/core';

export class Model2Repository extends DefaultCrudRepository<
    Model2,
    typeof Model2.prototype.id,
    Model2Relations
    > {
    constructor(
        @inject('datasources.DB') dataSource: DbDataSource,
    ) {
        super(Model2, dataSource);
    }
}

Json data post

{
  "address": "string",
  "status": 1,
  "createdAt": "2019-08-04T03:57:12.999Z",
  "updatedAt": "2019-08-04T03:57:12.999Z",
  "model1": {
     "id": "5d465b4cd91e484250d1e54b" /* id of exist item in table_1 */
  }
}

Controller is generate by lb4 controller

Expected:
- Item is save success into table_2 with EmbedsOne item of table_1.

Actual:
- Error:

{
    "error": {
        "statusCode": 422,
        "name": "ValidationError",
        "message": "The `Model2` instance is not valid. Details: `model1` is not defined in the model (value: undefined).",
        "details": {
            "context": "Model2",
            "codes": {
                "project": ["unknown-property"]
            },
            "messages": {
                "model1": ["is not defined in the model"]
            }
        }
    }
}
Huan Ho
  • 145
  • 2
  • 9

1 Answers1

0

TL;DR According to the Loopback 4 team, @embedsOne @embedsMany @referencesOne @referencesMany has not implemented yet (2019-Sep-03). (See docs or github)

But I found these decorators and their classes on the sourcecode So, hopefully, we have to wait untill the implementation is complete. I'll try to update this answer if I got anything new.

Salitha
  • 1,022
  • 1
  • 12
  • 32