You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose多数据库使用报错:TypeError: conn.Price is not a constructor

解决Mongoose多连接模型实例化报错问题

错误原因

用conn.model('Price', priceSchema)定义模型后,Mongoose不会自动把模型挂载为连接实例conn的属性,所以conn.Price是undefined,自然会触发TypeError: conn.Price is not a constructor报错。

两种解决方法

方法1:定义模型时直接赋值给变量

修改模型定义代码,将模型赋值给变量,后续用该变量创建实例:

const mongoose = require('mongoose');
const connectionOptions = { useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false };
const conn = mongoose.createConnection("mongodb://localhost/db_en", connectionOptions);

const Schema = mongoose.Schema;

const priceSchema = new Schema({
    fixed: {
        1: { type: Number, default: 199 }, 
        3: { type: Number, default: 499 }, 
        6: { type: Number, default: 729 },
        12: { type: Number, default: 999 }
    }
});

// 定义模型时直接赋值给变量
const Price = conn.model('Price', priceSchema);

之后创建实例并保存:

const ggg = new Price();
await ggg.save();

方法2:通过连接实例的model()方法获取模型

如果已经完成模型定义,也可以通过conn.model('Price')获取模型构造函数:

// 从连接实例中获取已定义的模型
const Price = conn.model('Price');
const ggg = new Price();
await ggg.save();

补充提示

如果是跨文件使用模型,建议在模型文件中导出Price模型,在业务代码中直接导入使用,避免重复定义或获取失败的情况。

内容的提问来源于stack exchange,提问作者user21189833

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:37:06