2017-05-06 73 views
0

我正在嘗試構建捐贈表單。我的代碼如下 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

您正在輸出物品{form:form},請注意情況。但是您正在導入並將其解構爲Form。更改爲小寫:

var {form} = require('./models/schema.js'); 
... 
var newMember = new form({...}); 

或者你也可以映射到一個新的varaible名字而descructurting,如果你想保持它作爲Form

var {form : Form} = require('./models/schema.js');