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

其他

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

相关推荐
“αβ”1 天前
MySQL表的操作
linux·网络·数据库·c++·网络协议·mysql·https
p***s911 天前
Spring数据库原理 之 DataSource
java·数据库·spring
虹科网络安全1 天前
艾体宝干货 | Redis Java 开发系列#1 从零开始的环境搭建与实践指南
java·数据库·redis
火山引擎开发者社区1 天前
火山引擎向量数据库 Milvus 版正式商业化:AI 时代的向量检索新标杆
数据库·milvus·火山引擎
神秘的土鸡1 天前
openEuler 25.09 企业级 MySQL主从复制部署与性能优化实战提升50%
linux·数据库·mysql·性能优化·openeuler
韩立学长1 天前
基于Springboot课堂教学辅助系统08922bq1(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
goxingman1 天前
Oracle视图基础
数据库·oracle
黎相思1 天前
MySQL索引特性
数据库·mysql
rit84324991 天前
压缩感知信号恢复算法:OMP与CoSaMP对比分析
数据库·人工智能·算法