不确定为什么会发生这种情况,请尝试删除所有new实例,然后从const切换为let。可以运行网站,但是当我通过html表单运行发布请求时,在“ const user = new UserSchema”等行上出现错误。类型错误:UserSchema不是构造函数。
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);
答案 0 :(得分:3)
您必须将架构指定为猫鼬模型。
var User= mongoose.model('user', UserSchema);