LoopBack4 MongoDB Auto Increment custom ID

loopback 4 auto-increment id
loopback auto generate id
loopback composite primary key
loopback aggregate mongodb

LoopBack itself is new for me and I see version 4 is way too different from version 3. My requirement is that I need to have a custom auto incremented id in my mongoDB document every time I create a POST to the REST end point similar to a running id in a MySQL database.

I did check this (auto-increment using loopback.js and MongoDB) and (https://gist.github.com/drmikecrowe/5a5568930bad567d4148aad75c94de5a) with a version 3 setup, but i did not find proper document to replicate the same on version 4.

Currently I am using a basic app with the out of the box REST implementations provided from the loopback 4. Below is an example of my model.

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);
  }
}

My mongodb document should look something like this:

{
  "_id" : ObjectId("5c373c1168d18c18c4382e00"),  
  "id"  : 1
  "name" : "aaaa",
  "val" : true
}
{
  "_id" : ObjectId("5c3869a55548141c0c27f298"),  
  "id"  : 2
  "name" : "bbbbb",
  "val" : false
}

You can do something like in this example

@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);
  }

you probably already noticed the auto-increment id feature. When you call the post API multiple times (leave id blank), the id increased by 1 every time. This feature is supported by the in-memory database. But we are using MongoDB in this project. If we want to have that feature, we need to do that programmatically.

For more information follow below link https://strongloop.com/strongblog/building-online-game-with-loopback-4-pt1/

see the section just above the API Explorer heading or find for 'auto increment id' you will be taken to that paragraph

Hopefully, this helps, write me if there is any other query. Thanks

How to let app insert id automatically? · Issue #811 · strongloop , In loopback 3, the id was inserted automatically. But for giving it a try to live on heroku, I needed to use postgres rather than mongodb. https://github.com/​dhmlau/loopback4-example-todo-customized (see Assuming you created the table outside of LoopBack, did you set up the auto-increment for that  MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents. However, there may be scenarios where we may want the _id field to have some auto-incremented value other than the ObjectId.

I'm also playing with Mongo and it can autogenerate your id for you.

Specifically, when you create your model, using lb4 model, choosing 'Entity' and then you're prompted:

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

This will generate your model with the property:

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

Great.. then when creating your CRUD controller:

? 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

Now when hitting your endpoint, the create POST doesn't take an ID, but will return one for you.

Honor type 'number' for auto-generated ids · Issue #165 · strongloop , The generated id is a string in the form: 55bef3c66b07d5602d1b93f6. For reference the mongoose-auto-increment module can add this See want to get rid of objectid altogether and use a simple incrementing number _id todo example not working with cloudant strongloop/loopback-next#2040. In loopback 3, the id was inserted automatically. But in loopback 4, it is required even when creating models. @property({ type: 'string', id: true, required: true }) id?: string; After removing the required: true option worked when I wa

You can do something like in this example

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

This will generate your model with the property:

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

Hopefully, this helps, please write me if there is any other code. Thanks

Proper way to create a sequence on a model property, I want it to start out with a value of 1 and increment each time a new model is created. /27745112/auto-increment-a-property-value-in-stronloop-loopback-​model model.id = getNextSequence('SpecialOrder');. next();. }; ``` The getNextSequence function would be a function wrapping the MongoDB reference above. MongoDB does not support auto-increment functionality as it is available in SQL databases. We all may be familiar with MongoDB’s 12-byte ObjectId which is used as a primary key to identify documents within a collection uniquely. But this is not fit for real-time operations in our day to day life.

MongoDB connector, Services · Interceptors · Life cycle events and observers · Routes · Sequence The following tutorial introduces how to set up MongoDB as the data source of LoopBack Entity { @property({ type: 'number', id: true, generated: true, }) id?: number; Important: Since in MongoDB _id is reserved for the primary key, LoopBack  I need to give each Unique User ID an auto increment id to mark a analytics datapoint in a bitarray/bitset. So the first user encounters would corresponding to the first bit of the bitarray, second user would be the second bit in the bitarray, etc. So is there a solid and fast way to generate incremental Unique User IDs in MongoDB?

MongoDB connector tutorial, I'm on loopback 4, I'm have two related tables, table A belongs to table B. I'm deleting row from table B, or tutorial available for how to create a custom LoopBack 4 connector? Can you explain the line "is the id generated automatically ? @fredlnl the id will be generated by your datasource for example mongodb would  Is there a built-in way to auto increment a model's property value is Strongloop loopback ? This model has a property named orderNumber and I want it to start at 1 and increment by 1 every time a new model is created. This model is persisted to a mongo DB.

strongloop/loopback, Let's take a look at the following example, which shows that the value of _id will be the result of an auto-incremented sequence:  LoopBack is a highly extensible, open-source Node.js and TypeScript framework based on Express that enables you to quickly create APIs and microservices composed from backend systems such as databases and SOAP or REST services.