【已解决】mongoose在mongodb中添加数据,数据库默认复数问题

Nodejs mongoose在mongodb中添加数据,数据库默认复数问题

问题描述

在ts项目内使用mangoose接入mangodb,向一个已有数据的表里添加数据。运行时总是自动创建一个新的表,并命名为复数。

已有的表假设命名是 'student (手动去敏)studentmodel继承基类basemodel,在constructor中super('student'),并调用基类中的数据插入方法。

studentModel文件

定义数据存储的key和传递参数数据校验类型

  • 创建model:
javascript 复制代码
export interface StudentRecord {
    Age: string;
    Name: string;
}
  • 创建schema
javascript 复制代码
const studentSchema = new mongoose.Schema({
    Age: String,
    Name: String
});
  • 建立class
javascript 复制代码
expert class StudentModel extends BaseModel{
	private Student:mongoose.Model<any>;
	constructor(colName:string){
		super('student');
		....	
	}
....
	async insertData(data:StudentRecord ):promise<any>{
		try{
			const res = await this.insertOne(data);
			return result;
		}
		....
	}
....
}

baseModel文件

  • 创建模型基类BaseModel,定义插入数据的函数
javascript 复制代码
export class BaseModel{
	protected model:mongoose.Model<any>;
	....
	constructor(colName:string){
		this.model = mongoose.models[colName]||mongoose.model(colName,baseSchema);
		....	
	}
	....
	// 数据创建函数
	    protect async insertOne(data: any): Promise<any> {
        try {
            return this.model.create(data);
        } 
        ....
    }
    ....
}

解决方法

把studentModel中插入数据的代码

javascript 复制代码
const res = await this.insertOne(data);

换成

javascript 复制代码
const res= await this.Student.insertOne(metadata);

原本是调用基类中的model.create,修改后调用子类Model的方法。

修改前会自动创建students表并插入数据,并且新建key '__v'。修改后数据放入student表中,但仍然会创建students表,新建表内无数据无key。

其他

虽然数据放置位置没问题,但如何让新的复数表不再生成。

相关推荐
小陈工16 小时前
Python Web开发入门(十七):Vue.js与Python后端集成——让前后端真正“握手言和“
开发语言·前端·javascript·数据库·vue.js·人工智能·python
科技小花21 小时前
数据治理平台架构演进观察:AI原生设计如何重构企业数据管理范式
数据库·重构·架构·数据治理·ai-native·ai原生
一江寒逸21 小时前
零基础从入门到精通MySQL(中篇):进阶篇——吃透多表查询、事务核心与高级特性,搞定复杂业务SQL
数据库·sql·mysql
D4c-lovetrain21 小时前
linux个人心得22 (mysql)
数据库·mysql
阿里小阿希1 天前
CentOS7 PostgreSQL 9.2 升级到 15 完整教程
数据库·postgresql
荒川之神1 天前
Oracle 数据仓库雪花模型设计(完整实战方案)
数据库·数据仓库·oracle
做个文艺程序员1 天前
MySQL安全加固十大硬核操作
数据库·mysql·安全
不吃香菜学java1 天前
Redis简单应用
数据库·spring boot·tomcat·maven
一个天蝎座 白勺 程序猿1 天前
Apache IoTDB(15):IoTDB查询写回(INTO子句)深度解析——从语法到实战的ETL全链路指南
数据库·apache·etl·iotdb
不知名的老吴1 天前
Redis的延迟瓶颈:TCP栈开销无法避免
数据库·redis·缓存