【问题标题】:Mongoose model - TypeError: Account is not a constructorMongoose 模型 - TypeError:帐户不是构造函数
【发布时间】:2018-03-25 07:54:58
【问题描述】:

我正在尝试在 account.js 中定义一个模型并将其导出到我的 server.js 文件中。当我尝试创建模型的新实例时,出现此错误:

"TypeError: Account is not a constructor

这可能是一个简单的错误,但我不明白为什么它没有将其识别为构造函数。

这些是我的文件:

account.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;    
const accountSchema = new Schema({
    fullname:{
        type: String,
        required: true,
    },
    username:{
        type: String,
        required: true,
        unique: true,
    }
}, {
    collection: 'accounts',
});

mongoose.connect('mongodb://localhost/accountsdb', (error) => {
    if(error) console.log(error);   
    console.log("Database connection successful."); 
});

module.exports = mongoose.model('Account', accountSchema);

服务器.js

var express = require('express');
var router = express.Router();

var bodyParser = require('body-parser');
const Account = require("account");

var app = express();
app.use(express.static('assets'));

app.use(bodyParser.json());   
app.use(bodyParser.urlencoded({extended: true}));

app.get('/', function(req, res) {
    res.sendFile('index.html', {root : __dirname + '/'});
});

app.post('/signup', function(req,res){
    console.log(req.body);
    const newAccount = new Account(req.body);     //ERROR here
    newAccount.save((err) => {
        if(err) throw err;
        res.redirect('/');
    });   
});

app.use(express.static(__dirname + '/'));

app.listen(3000);
console.log('Listening on port 3000');

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    在您的server.js 中,您对Account 的导入是错误的。改为这样导入:

    const Account = require("./account");
    

    【讨论】:

      【解决方案2】:

      这里的问题在于您需要Account 的方式。如果在require('account') 中没有以account 为前缀的“/”、“./”或“../”,它会尝试导入核心模块或 node_modules 之一(如果在主目录中)。

      【讨论】:

        猜你喜欢
        • 2017-04-08
        • 2017-03-09
        • 2019-03-12
        • 2018-08-22
        • 2019-05-09
        • 2018-05-24
        • 2017-08-02
        • 2018-01-29
        • 2019-08-14
        相关资源
        最近更新 更多