使用Mongoose模型实例化时报TypeError: account is not a constructor如何解决
问题排查与修复方案
- 模型导入语法错误
路由代码中导入模型时缺少require关键字,当前代码const account = ('../schemas/account_schema');实际是将字符串赋值给account变量,并非导入Mongoose模型,字符串类型自然无法作为构造函数调用。 - 作用域变量同名覆盖
路由处理函数内部重新声明了和外层导入的模型同名的account变量,触发变量提升后,当前作用域内的account在赋值前为undefined,调用new account()自然报错。 - 模型配置语法错误
定义Schema时,配置项的timestamps属性写法错误,对象字面量应使用冒号:赋值,你当前写的是等号=,会直接触发语法错误。
修复后的代码
1. 模型代码
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const accountSchema = new Schema({ account_id: { type: String, required: true }, available_balance: { type: Number } }, { timestamps: true }) module.exports = mongoose.model('Account', accountSchema);
2. 路由代码
const express = require('express'); const router = express.Router(); const Account = require('../schemas/account_schema'); router.post('/account_card/', (req, res) => { var account = new Account(); // 后续业务逻辑 });
内容的提问来源于stack exchange,提问作者ChacaLitos
相关产品推荐
相关产品推荐

