3
votes

I want to store key value pairs to a MongoDB using TypeORM. My backend API is made with NestJs (not sure if this is important). The key is of type string and the value is of type object because I want to store anything to this object.

This is my TypeORM database configuration

TypeOrmModule.forRoot({
  type: 'mongodb',
  host: 'localhost',
  port: 27017,
  database: 'nest',
  entities: [`${__dirname}/**/*.entity.{ts,js}`],
  synchronize: true,
}),

My mapping entity does not auto generate the key because I want to set it on my own

@Entity()
export class Mapping extends BaseEntity {
  @PrimaryColumn()
  key: string;

  @Column()
  value: object;
}

When I want to save a new mapping to the database I run this logic (it doesn't matter where)

  const newMapping: Mapping = new Mapping();
  newMapping.key = 'foobar';
  newMapping.value = { foo: 'bar' };
  await newMapping.save();

I'm getting this error

TypeError: Cannot read property 'propertyName' of undefined

when executing the save function of the database entity. It seems that I can't store the value of type object to the database. Any solutions for this?

2
What if you rename your id column from key to id?hlfrmn
Hey, I updated my code and use id instead of key now. Unfortunately the error remains the samehrp8sfH4xQ4
Can you change decorator from PrimaryColumn to ObjectIdColumn?hlfrmn

2 Answers

1
votes

When working with TypeORM + Mongo, your entities must have their ID columns decorated with the ObjectIdColumn decorator, e.g.

import {Entity, ObjectID, ObjectIdColumn, Column} from "typeorm";

@Entity()
export class Mapping {

    @ObjectIdColumn()
    key: ObjectID;

    @Column()
    value: ;
}

Defining entities and columns is almost the same as in relational databases, the main difference is that you must use @ObjectIdColumn instead of @PrimaryColumn or @PrimaryGeneratedColumn.

TypeORM Mongo Docs

1
votes

You can try NestJS support for MongoDB.

TypeORM has basic MongoDB support. Most of TypeORM functionality is RDBMS-specific, this page contains all MongoDB-specific functionality documentation. typeorm docs.

Instead try to use NestJS approach. They built a module for MongoDB, it's a bit more code to write but is much more into mongo than Typeorm. It uses npm mongoose package. I currently use this and it works very good and it's not that hard to implement.

Here are their docs on NestJS / MongoDB. MongoDB | NestJS

Hope this helps you!