我正在尝试建立一个捐赠表格。我的代码如下 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.');
});
表单模型
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};
当我运行GET请求时,我获取了数据库中的所有数据,但是当我发送POST请求时,我收到错误“TypeError:Form不是构造函数 在app.post(... / server / server.js:22:19)“。如何修复此错误?我认为错误来自于我如何调用新表单但我对代码所做的所有调整都没有似乎没有解决它。
答案 0 :(得分:0)
您正在导出对象{form:form}
,请注意这种情况。但是您将其导入并解构为Form
。改为小写:
var {form} = require('./models/schema.js');
...
var newMember = new form({...});
另外,如果你想将它保持为Form
,你也可以在descructurting时映射到一个新的可变名称:
var {form : Form} = require('./models/schema.js');