使用Express将表单数据导入mongoDB数据库
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Express将表单数据导入mongoDB数据库相关的知识,希望对你有一定的参考价值。
我试图从html表单获取表单数据并尝试将其保存到MongoDB数据库。我正在使用带有Express的Nodejs。
可能是什么问题,每当我点击提交按钮时,它都显示未找到并且它也没有保存数据。
这是我到目前为止所做的。
var express = require('express');
var router = express.Router();
var app = express();
var mongoose = require('mongoose');
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
var db=mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error'));
var Schema = mongoose.Schema;
var questionSchema = new Schema({
sectors: String,
Qid: String,
Question: String,
enabled: Boolean
},{collection:'questionPool'});
var questionModel = mongoose.model('questionModel', questionSchema);
router.get('/', function(req,res){
res.render("addQuest");
});
router.post('/add', (req,res) =>{
var questionData = new questionModel(req.body);
questionData.save()
.then(item =>{
res.send("Information saved to database");
})
.catch(err =>{
res.status(400).send("Unable to save to database");
});
});
module.exports = router;
addQuest.jade
doctype html
html
head
title Add Questions
body
center
form(method='post', action='/add')
label Enter Your Name
br
input(type='text', name='sector', placeholder='Enter Sector', required='')
input(type='text', name='Qid', placeholder='Enter Qid', required='')
input(type='text', name='Question', placeholder='Enter your Question', required='')
input(type='boolean', name='enabled', placeholder='Enabled or Disabled', required='')
input(type='submit', value='Add Question')
答案
我试过你的代码它对我来说很好。通过控制台检查MongoDB中存在名称my_database的数据库。您的代码没有问题。
以上是关于使用Express将表单数据导入mongoDB数据库的主要内容,如果未能解决你的问题,请参考以下文章
通过表单从不同字段上传多个文件并使用express multer存储到mongodb数据库中
使用 mongoose 将表单数据插入 mongodb 时出现莫名其妙的行为