Loopback4 Model Definition options for mongodb collection name

554 views Asked by At

I am using loopback 4 and trying to configure the Model annotation with properties to configure how the collection is created in Mongo.

I have a Model called say Client and I want the collection in Mongo to be called Clients. The cross over with documentation is confusing, as they reference the properties from v3 in v4 docs.

I have tried this:

import {Entity, model, property} from '@loopback/repository';

@model({
  settings: {strict: false},
  name: 'client',
  plural: 'clients',
  options: {
    mongodb: {
      collection: 'clients',
    },
  },
})
export class Client extends Entity {
  @property({
    type: 'string',
    id: true,
    defaultFn: 'uuidv4',
    index: true,
  })
  id: string;

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

  @property({
    type: 'string',
  })
  code?: string;

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

With no Joy, still creates the collection as the Class name Client

2

There are 2 answers

1
Marvin Irwin On

This is from 2014, but perhaps it still works. Try not putting the mongodb key options

  settings: {strict: false},
  name: 'client',
  plural: 'clients',
  mongodb: {
    collection: 'clients',
  },
0
Miroslav Bajtoš On

Please note that all model settings must be nested inside settings property, LB4 does not support top-level settings yet.

Also the option plural is not used by LB4 as far as I know.

I think the following code should work for you:

@model({
  name: 'client',
  settings: {
    strict: false
    mongodb: {
      collection: 'clients',
    },
  },
})
export class Client extends Entity {
  // ...
}

UPDATE: I opened a GitHub issue to discuss how to make @model decorator easier to use for users coming from LB3. See https://github.com/strongloop/loopback-next/issues/2142