【问题标题】:TypeError: UserSchema is not a constructor (Schema is not a constructor MongoDB)TypeError: UserSchema is not a constructor (Schema is not a constructor MongoDB)
【发布时间】:2018-09-16 05:53:18
【问题描述】:

不确定为什么会发生这种情况,尝试删除所有 new 实例,从 const 切换到 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);

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您必须将架构分配为猫鼬模型。

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

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 2018-05-24
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多