Search code examples
arraysmongodbmodelobjectidloopback4

Is there a way to create one array properties with many mongoDB objectiID inside


I use Loopback4. When i want to add a mongoDb ObjectId property inside my model i do that :

    @property({
        type: 'string',
        mongodb: {dataType: 'ObjectID'},
    })
    organizationId?: string;

Now i want to make an array with MongoDB ObjectId properties inside, so i tried to do :

    @property({
        type: 'array',
        itemType: 'string',
        mongodb: {dataType: 'ObjectID'},
    })
    tagsId?: string[];

but it seems like all the array is converted to one ObjectID inside the mongoDb.

What I want to do is to simply get an array with many ObjectId inside. I tried everything in my knowledgme: that was not enough.


Solution

  • i found a solution : Step 1 : create a model with just one id. Step 2 : Make an array with your new model

    Step 1 : In your future model (in my case : tagReference) :

    @model()
    export class TagReference extends Entity {
        @property({
            type: 'string',
            mongodb: {dataType: 'ObjectID'},
        })
        id?: string;
    
        constructor(data?: Partial<TagReference>) {
            super(data);
        }
    }
    

    Step 2: Where you want your array :

    import {TagReference} from './tag-reference.model';
    
    @model()
    export class Resource extends BaseEntity {
    
        // ...
    
        @property({
            type: 'array',
            itemType: TagReference,
        })
        tagIds?: string[];
    
       // ...
    }