LoopBack4 MongoDB自定义自增ID

3
LoopBack本身对我来说是新的,我发现版本4与版本3有很大不同。我的要求是,每次我创建一个POST到REST端点时,我需要在我的mongoDB文档中拥有一个自定义的自动递增ID,类似于MySQL数据库中的运行ID。
我检查了这个(auto-increment using loopback.js and MongoDB)和(https://gist.github.com/drmikecrowe/5a5568930bad567d4148aad75c94de5a),但是我没有找到适当的文档来在版本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
}
4个回答

0

我也在使用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

现在当访问您的端点时,创建POST不需要ID,但会为您返回一个ID。

0
这个类继承了DefaultCrudRepository类并重写了create方法。该方法使用“Counters”集合来保存当前数据类(this.entityClass.name)的最后一个id。findAndModify方法将防止创建重复的id值。
import {DefaultCrudRepository, Entity, DataObject, Options} from '@loopback/repository';

export class MongoAutoIncIdRepository<T extends Entity, ID, Relations extends object = {}> extends DefaultCrudRepository<T, ID, Relations> {

  public async create(entity: DataObject<T>, options?: Options): Promise<T> {
    if (!this.dataSource.connected) {
      await this.dataSource.connect()
    }
    
    let mongoConnector = this.dataSource.connector!

    let collection = mongoConnector.db.collection('Counters')

    let result = await collection.findAndModify(
      {
        collection: this.entityClass.name
      },
      [['_id', 'asc']],
      {
        $inc: {value: 1}
      },
      {
        upsert: true,
        new: true
      })

    console.log(result)
    // @ts-ignore
    entity.id = result.value.value
    return super.create(entity, options)
  }

}

使用起来很容易。如果需要自动增量,请不要从DefaultCrudRepository继承您的存储库,而是从MongoAutoIncIdRepository继承。然后,当调用create方法时,id将自动增加1。


1
虽然这可能是好的代码,但它并没有解释任何东西。请添加一些说明为什么它能够工作。 - mydoglixu
1
添加了描述 - Дмитрий Лац

0

你可以像这个例子一样做些什么

let last_record = await this.testRepository.findOne({order: ['id DESC']});
if(last_record) invoice.id = last_record.id+1;

这将使用该属性生成您的模型:

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

希望这有所帮助,请给我写信,如果有其他的代码。谢谢。

0

你可以像这个例子一样做些什么

@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 Explorer标题上方的部分,或者搜索“auto increment id”,您将被带到该段落。

希望这可以帮助您,如果有任何其他问题,请写信给我。 谢谢


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接