Search code examples
node.jsmongodbtypeorm

TypeOrm and MongoDB, inserts not appearing in database


I get a connection the following way:

async function getMongoConnection(): Promise<Connection> {
    const connection: Connection = await createConnection({
        type: "mongodb",
        host: "localhost",
        port: 27017,
        database: "test",
        synchronize: true,
        logging: true,
        entities: [
            File
        ]
    });

    return connection;
}

export { getMongoConnection };

and I have the following entity definition:

@Entity({
    name: "files"
})
export class File {
    @ObjectIdColumn()
    id: ObjectID;

    @Column()
    filePath: string;

    @Column()
    fileSize: number;
}

When I'm running a "save" or "insert" call, it seems to work fine, but running "find" on the manager throws a Cannot read property 'prototype' of undefined error. The collection doesn't appear in the database either when I'm checking it with MongoDB Compass.
However, manager.stats(File).count is incrementing just fine.

Here's the last bit of related code:

async function saveFileEntry(filePath: string) {
    const manager = (await mongoConnection).mongoManager;
    console.log(await (await (manager.stats(File))).count);

    const file = new File();
    file.filePath = filePath;
    file.fileSize = fs.statSync(filePath).size;

    manager.save(file)
    .then( (value) => {
        console.log("Saved file:");
        console.log(value);

        manager.find(File)
        .then( (files) => {
            files.forEach( (file) => {
                console.log("Found file:");
                console.log(file);
            });
        })
        .catch( (error) => {
            console.log(`Couldn't find file: ${error}`)
        });
    })
    .catch( (error) => {
        console.log(`Couldn't save file: ${error}`);
    });
}

Solution

  • TypeOrm and MongoDb just don't work together well as of the time this answer was written.
    We ended up switching to Postgres and the same code worked right away with minimal changes.

    If you come upon this question with the same problem: Too Bad!