首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用关系保存数据(Nodejs / loopback 4/ mongoDB)

用关系保存数据(Nodejs / loopback 4/ mongoDB)
EN

Stack Overflow用户
提问于 2019-08-04 13:28:56
回答 1查看 294关注 0票数 0

我不能发布带有关系对象的数据json。

我使用mongoDB。

我有3张桌子: table_1,table_2,table_3。

我创建了EmbedsManyEmbedsOne关系

table_1.

  • table_2
  • table_2 EmbedsOne EmbedsMany table_3。

我不知道创建post data json来创建一个包含table_1项的新table_2项。

代码语言:javascript
运行
复制
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;

存储库模型2

代码语言:javascript
运行
复制
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数据发布

代码语言:javascript
运行
复制
{
  "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 */
  }
}

控制器由lb4 controller生成

期望值:

  • 项目正在使用table_1的EmbedsOne项目成功保存到table_2中。

实际:

  • Error:

代码语言:javascript
运行
复制
{
    "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"]
            }
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-09-03 23:59:24

根据Loopback 4团队的说法,@embedsOne @embedsMany @referencesOne @referencesMany尚未实施(2019年9月03日)。(参见docsgithub)

但是我在sourcecode上找到了这些装饰器和它们的类,所以,希望我们必须等到实现完成。如果我有什么新的东西,我会试着更新这个答案。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57344070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档