将表单输入插入mongoDB

时间:2019-04-12 23:43:28

标签: node.js reactjs mongodb express mongoose

我正在尝试将通过表单提交的会议室名称和会议室状态插入猫鼬数据库中的会议室集合。当我单击提交时,将使用dateCreated和dateEdited插入一个新房间,但房间名称和状态未插入数据库。

房间型号:

var mongoose = require('mongoose');
var room = new mongoose.Schema({
    room: String,
    created: {type:Date, default:Date},
    edited: {type:Date, default:Date},
    status: String
})
module.exports = mongoose.model("Room", room);

Room.js(表单代码):

<Modal visible={this.state.visible} width="400" height="300" effect="fadeInUp" onClickAway={()=>this.closeModal}>
            <div>
                <form method="POST" action="/api/room">
                  <label>Room name: </label>
                  <input type='text' placeholder="Room name" name="roomName" required/>  <br></br>
                  <label>Status: &emsp;&emsp;&nbsp;&nbsp; </label>
                  <select id="sel1" name="status" required>
                  <option>Active</option>
                  <option>Inactive</option>
                  </select>
                  <input type="submit" value="submit"/>       
                </form>
                <button onClick={this.closeModal}>Close</button>
            </div>
            </Modal>

Room.js路线:

var express = require('express');
var router = express.Router();
var Rooms = require('../models/Rooms');
var bodyParser = require('body-parser');

router.use(bodyParser.json())
router.use(bodyParser.urlencoded({extended: true}));



/* GET ALL ROOMS */
router.get('/api/room', function(req, res, next) {
  Rooms.find((err, results)=>{
    if(err) throw err;
    res.header("Content-Type",'application/json');
    res.send(JSON.stringify(results, null, 4));
  });
}); 

/* SAVE ROOMS */

router.post("/api/room", (req,res)=>{
  var data = new Rooms(req.body);
  console.log(data);
  data.save()
    .then(item=>{
      res.send('room added to db');
    })
    .catch(err=>{
      res.status(400).send("unable to save to db")
    });
});


module.exports = router;

0 个答案:

没有答案