本文介绍了TypeError:UserSchema不是构造函数(Schema不是MongoDB的构造函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
不确定为什么会发生这种情况,请尝试删除所有new实例,然后从const切换为let.可以运行站点,但是当我通过html表单运行发布请求时,在"const user = new UserSchema"等行出现错误. TypeError:UserSchema不是构造函数.
Not sure why this is happenening, tried removing all instances of new, switching to let from const ect. Can run site however when I run a post request via a html form, get an error on the line "const user = new UserSchema" ect. of TypeError: UserSchema is not a constructor.
const express = require('express');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bodyParser = require('body-parser');
let app = express();
let mongoDB = //hiding url for obvious reasons
mongoose.connect(mongoDB, { useNewUrlParser: true });
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
const UserSchema = new Schema({
name: String,
email: String
});
app.set('view engine', 'ejs');
app.use('/assets', express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function(req,res){
res.render('landingPage');
});
app.post('/', function (req, res) {
const user = new UserSchema(req.body.name, req.body.email);
user.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.listen(3000);
推荐答案
您必须将架构指定为猫鼬模型.
You have to assign the schema as a mongoose model.
var User= mongoose.model('user', UserSchema);
这篇关于TypeError:UserSchema不是构造函数(Schema不是MongoDB的构造函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!