gpt4 book ai didi

javascript - 类型错误 : UserSchema is not a constructor (Schema is not a constructor MongoDB)

转载 作者:行者123 更新时间:2023-11-30 11:14:06 25 4
gpt4 key购买 nike

不确定为什么会这样,尝试删除所有 new 实例,从 const ect 切换到 let。可以运行站点,但是当我通过 html 表单运行发布请求时,在“const user = new UserSchema”等行中出现错误。 TypeError: 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);

最佳答案

您必须将模式分配为 Mongoose 模型。

var User= mongoose.model('user', UserSchema);

关于javascript - 类型错误 : UserSchema is not a constructor (Schema is not a constructor MongoDB),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52349100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com