Py学习  »  MongoDB

LoopBack4 MongoDB自动递增自定义ID

Shades • 4 年前 • 654 次点击  

环回本身对我来说是新的,我看到版本4和版本3太不一样了。我的要求是,每次创建到REST端点的POST时,都需要在mongoDB文档中有一个自定义的自动递增id,类似于MySQL数据库中的运行id。

我查过了( auto-increment using loopback.js and MongoDB )以及( https://gist.github.com/drmikecrowe/5a5568930bad567d4148aad75c94de5a )有了版本3的设置,但是我没有找到合适的文档在版本4上复制相同的内容。

目前,我正在使用一个基本的应用程序,其中包含loopback 4提供的开箱即用REST实现。下面是我的模型的一个例子。

export class Test extends Entity {
  @property({
   type: 'string',
   id: true,
  })
  _id?: string;

  @property({
   type: 'number',
   generated: true,
   required: false
  })
  id: number;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @property({
    type: 'boolean',
    required: true,
  })
  val: boolean;

  constructor(data?: Partial<Test>) {
    super(data);
  }
}

我的mongodb文档应该如下所示:

{
  "_id" : ObjectId("5c373c1168d18c18c4382e00"),  
  "id"  : 1
  "name" : "aaaa",
  "val" : true
}
{
  "_id" : ObjectId("5c3869a55548141c0c27f298"),  
  "id"  : 2
  "name" : "bbbbb",
  "val" : false
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51809
 
654 次点击  
文章 [ 2 ]  |  最新文章 4 年前
ticktock
Reply   •   1 楼
ticktock    4 年前

我也在玩Mongo,它可以自动生成你的id。

具体来说,当您使用lb4 model创建模型时,选择“Entity”,然后系统会提示您:

Let's add a property to Participant
Enter an empty property name when done

? Enter the property name: id
? Property type: string
? Is id the ID property? Yes
? Is id generated automatically? Yes

这将生成具有以下属性的模型:

  @property({
    type: 'string',
    id: true,
    generated: true,
  })
  id?: string;

伟大的。。然后在创建CRUD控制器时:

? What kind of controller would you like to generate? REST Controller with CRUD functions
? What is the name of the model to use with this CRUD repository? Person
? What is the name of your CRUD repository? PersonRepository
? What is the name of ID property? id
? What is the type of your ID? string
? Is the id omitted when creating a new instance? Yes
? What is the base HTTP path name of the CRUD operations? /persons

现在,当到达您的端点时,create POST不接受ID,但将返回一个ID给您。

Yash Rahurikar
Reply   •   2 楼
Yash Rahurikar    4 年前

你可以在这个例子中做类似的事情

@post('/characters', {
    responses: {
      '200': {
        description: 'Character model instance',
        content: {'application/json': {schema: {'x-ts-type': Character}}},
      },
    },
  })
  async create(@requestBody() character: Character): Promise<Character> {
    //add following lines
    let characterId = 1;
    while(await this.characterRepository.exists(characterId)){
      characterId ++;
    }
    character.id = characterId;

    //add above lines
    return await this.characterRepository.create(character);
  }

您可能已经注意到了自动递增id特性。当您多次调用post API时(将id留空),id每次增加1。内存数据库支持此功能。但是我们在这个项目中使用MongoDB。如果我们想拥有这个功能,我们需要通过编程来实现。

更多信息请点击以下链接 https://strongloop.com/strongblog/building-online-game-with-loopback-4-pt1/

请参阅API资源管理器标题上方的部分 或查找“自动增量id”,您将被带到该段落

希望这能帮上忙,如果还有其他问题,请写信给我。 谢谢