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

其他

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

相关推荐
非凡ghost2 小时前
AOMEI Partition Assistant磁盘分区工具:磁盘管理的得力助手
linux·运维·前端·数据库·学习·生活·软件需求
恣艺2 小时前
Redis是什么?一篇讲透它的定位、特点与应用场景
数据库·redis·缓存
天天爱吃肉82182 小时前
【比亚迪璇玑架构深度解析:重新定义智能电动汽车的“整车智能”】
数据库·人工智能·嵌入式硬件·架构·汽车
一成码农3 小时前
MySQL问题8
数据库·mysql
axban3 小时前
QT M/V架构开发实战:M/V架构的初步认识
开发语言·数据库·qt
Dontla3 小时前
Docker Compose healthcheck介绍(监控容器中服务的实际健康状态)数据库健康检查pg_isready
数据库·docker·容器
semantist@语校3 小时前
第十九篇|东京世界日本语学校的结构数据建模:制度函数、能力矩阵与升学图谱
数据库·人工智能·线性代数·矩阵·prompt·github·数据集
数巨小码人3 小时前
Oracle SQL调优技巧实战指南
数据库·sql·oracle
noravinsc3 小时前
在银河麒麟v10上安装达梦8数据库
服务器·数据库·oracle