node.js - 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}`);
});
}
解决方案
在编写此答案时,TypeOrm 和 MongoDb 不能很好地协同工作。
我们最终切换到 Postgres,同样的代码只需很少的改动就可以立即工作。
如果你遇到同样的问题:太糟糕了!
推荐阅读
- react-native - 基于 React Native (expo) cookie 的身份验证仅在本地工作
- python - VScode - pylance 没有正确识别错误,而 Jedi 没有正确标记错误
- eclipse - Eclipse 插件:如何将“java.lang.string”转换为 IEditorInput?
- blockchain - tx.wait 与 Ethers.js 永远不会解决
- c# - 选择具有类的某些属性的字典
- php - 如何能够通过 CSV 接收不同格式的日期,并将它们同质化为 MySQL / MariaDB 处理的格式?
- javascript - 如何将计算属性与嵌套 v-for 循环内的引导弹出框匹配?
- python - 从 Apache 上的 Python 脚本传输 AWS S3
- java - 如何使用 Thymeleaf 创建可点击项目列表
- android - 在没有确切内核源代码和配置的情况下构建 android 内核模块