【已解决】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。

其他

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

相关推荐
l1t几秒前
DeepSeek总结的 DuckDB 1.5 功能亮点
数据库·sql·duckdb
Bdygsl8 分钟前
MySQL(4)—— 表设计
数据库·mysql
2301_8194143012 分钟前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
2401_8589368820 分钟前
51 单片机核心知识点:GPIO、中断、定时器与蜂鸣器驱动
单片机·mongodb·nosql
未来龙皇小蓝30 分钟前
【MySQL-索引调优】09:Order By相关概念
数据库·mysql·性能优化
未来龙皇小蓝33 分钟前
【MySQL-索引调优】10:常见的分页优化处理
数据库·mysql·性能优化
God__is__a__girl37 分钟前
Oracle驱动版本引发ORA-01461批量插入异常排查与解决
数据库·oracle
少年攻城狮1 小时前
Oracle系列---【两个环境,表结构一致,数据量一致,索引也一致,为什么同样的sql执行时间却不一致?】
数据库·sql·oracle
l1t1 小时前
解决用docker安装umbra数据库遇到的FATAL:Operation not permitted错误
数据库·docker·容器
2401_894241921 小时前
机器学习与人工智能
jvm·数据库·python