Mongoose模型 - TypeError:Account不是构造函数

时间:2018-03-24 22:37:59

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

我尝试在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);

Server.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');

2 个答案:

答案 0 :(得分:1)

server.js中,Account的导入错误。像这样导入:

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

答案 1 :(得分:1)

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