首页 > 解决方案 > TypeOrm 和 MongoDB,插入未出现在数据库中

问题描述

我通过以下方式获得连接:

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

我有以下实体定义:

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

    @Column()
    filePath: string;

    @Column()
    fileSize: number;
}

当我运行“保存”或“插入”调用时,它似乎工作正常,但在管理器上运行“查找”会引发Cannot read property 'prototype' of undefined错误。当我使用 MongoDB Compass 进行检查时,该集合也不会出现在数据库中。
但是,manager.stats(File).count增加就好了。

这是相关代码的最后一点:

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

标签: node.jsmongodbtypeorm

解决方案


在编写此答案时,TypeOrm 和 MongoDb 不能很好地协同工作。
我们最终切换到 Postgres,同样的代码只需很少的改动就可以立即工作。

如果你遇到同样的问题:太糟糕了!


推荐阅读