Friday, 5 May 2017

schema is not a constructor

I am trying to build a donation form. My code is as follows server.js

const express = require('express');
const bodyParser = require('body-parser');

var {mongoose} = require('./db/db.js');
// var {Form} = require('./models/form.js');
var {Form} = require('./models/schema.js');
var app = express();
app.use(bodyParser.json());


app.get('/', function(req, res) {
  res.send('ok');
});
//private
app.get('/form', (req, res) => {
  mongoose.model('Form').find((err, form) => {
      res.send(form);
  });
});
//makes new member
app.post('/form', (req, res) => {
  var newMember = new Form({
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    email: req.body.email,
    phoneNumber: req.body.phoneNumber,
    donation: req.body.donation,
    shirt: req.body.shirt
  });
  newMember.save().then((doc) => {
    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  });
});

app.listen(3000, () => {
  console.log('Listening on port 3000.');
});

And the form model

const mongoose = require('mongoose');
var Schema = mongoose.Schema;

var formSchema = new Schema({
  firstName: {
    type: String,
    required: true,
    minlength: 1,
    trim: true
  },
  lastName: {
    type: String,
    required: true,
    minlength: 1,
    trim: true
  },
  email: {
    type: String,
    required: true,
    minlength: 1,
    trim: true
  },
  phoneNumber: {
    type: Number,
    trim: true,
    minlength: 7,
    required: false
  },
  donation: {
    type: Number,
    required: true
  },
  shirt: {
    type: Boolean
  }
});
var form = mongoose.model('Form',formSchema);
module.exports = {form};

When I run the GET request I get all the data in the database but when I send a POST request I get the error "TypeError: Form is not a constructor at app.post (.../server/server.js:22:19)". How do I fix this error? I think the error comes from how I am calling new Form but all the tweaks I make to the code don't seem to fix it.



via Sam Roehrich

No comments:

Post a Comment