[英]How do I POST data into MongoDB database using node.JS?
the code below is pretty messy so don't judge too much!下面的代码很乱所以不要判断太多! I am trying to POST a basic user profile into my database, i don't think i am far off but i keep getting a 404.
我正在尝试将基本用户配置文件发布到我的数据库中,我认为我离得很远,但我一直收到 404。
im pretty knew to all of these technologies so could somebody please enlighten me as to what i have done wrong.我非常了解所有这些技术,所以有人可以告诉我我做错了什么。
node.js POST method node.js POST 方法
var express = require('express');
var router = express.Router();
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/local';
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('signIn', { title: 'signIn' });
});
router.get('/getData', function(req, res, next){
mongo.connect(url, function (err, db) {
assert.equal(null, error);
var cursor = db.collection('userData').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close();
res.render('index', {items: resultArray});
} );
});
});
router.post ('/insert', function(req,res,next) {
var item = {
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
password: req.body.password
};
mongo.connect(url, function (err, db) {
assert.equal(null, err);
db.collection('userData').insertOne(item, function (err, result) {
assert.equal(null, err);
console.log('item has been inserted');
db.close;
});
});
res.redirect('/');
});
module.exports = router;
form HTML表单 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>SignIn Page</title>
<link rel="stylesheet" type="text/css" href="/stylesheets/signIn.css"/>
</head>
<body>
<div class="background">
<div class="loginFormWrapper">
<form action="/users/submit" method="POST">
<div class="loginForm">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="first name">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastName" name="lastName" placeholder="last name">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email" id="email" placeholder="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" name="password" id="password" placeholder="password">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<form action="users" method="GET">
<button type="submit" class="btn btn-default">get result</button>
</form>
</div>
</div>
</body>
</html>
App.js应用程序.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var validate = require('form-validate');
var mongoose = require('mongoose');
var index = require('./routes/index');
var users = require('./routes/users');
var About = require('./routes/about');
var signIn = require('./routes/signIn');
var contact = require('./routes/contact');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/About', About);
app.use('/signIn', signIn);
// app.use('/contact', contact);
//catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
user.js用户.js
var express = require('express');
var app = require("mongoose");
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
A quick reminder, the post() method just gets the data from the <form>
you specify.快速提醒一下, post() 方法只是从您指定的
<form>
获取数据。 For you to be able to get that data you'd have to do something like this.为了能够获得这些数据,你必须做这样的事情。
app.js应用程序.js
const express = require('express)
const mongoose = require('mongoose)
var app = express()
mongoose.connect('mongodb://localhost:"yourPortHere"/"mongoDBhere"')
Now post needs the body parser in order to be able to retrieve the data and sort of "translate it" to JS, for that you need the body parser.现在 post 需要正文解析器,以便能够检索数据并将其“翻译”为 JS,为此您需要正文解析器。
app.use(bodyParser.urlencoded({extended: false})) //Post Body Parser
Now let's get to the post现在让我们进入帖子
app.post("/action", (req, res) => {
var userData = {
username: req.body.username,
password: req.body.password
}
For the moment userData is going to hold the data you just retrieved from the <form>
Remember that action="/YourActionHere
is the identifier for the app.post("/YourActionHere")
so those two have to match, otherwise you will not get the data.目前 userData 将保存您刚刚从
<form>
检索到的数据 请记住action="/YourActionHere
是app.post("/YourActionHere")
的标识符,因此这两个必须匹配,否则您将不会获取数据。
To save it to MongoDB you first need to create a model of the object you want to store, if MongoDB has a Database named movies with a directory named films on it you first have to create a Model named film since mongoose will save it in the directory films (<- By directory I mean collection)将它保存到MongoDB的,你首先需要创建要存储的对象的模型,如果MongoDB中有一个名为它电影目录数据库命名的电影,你首先要创建一个型号命名电影,因为猫鼬将其保存在目录电影(<- 目录我指的是收藏)
So: in folder Models you create a model of the object所以:在文件夹模型中,您创建对象的模型
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var film = new Schema({
title: String,
year: String,
director: String
})
module.exports = mongoose.model("movie", movieSchema)
To be able to use that new Schema you have to import it in you app.js with为了能够使用该新架构,您必须将其导入 app.js 中
var Film = require('pathToFilmSchema')
Now in your post you will save userData to that Schema, and mongoose will store it in the collection specified in its .js.现在,在您的帖子中,您将 userData 保存到该 Schema,并且 mongoose 会将其存储在其 .js 中指定的集合中。
app.post("/action", (req, res) => {
var userData = {
title: req.body."name",
year: req.body."name",
director: req.body.""
}
new Film(userData)
})
If the structure is the same de Data in that variable will be stored in a Schema, then you just have to call the method .save()
, which you can call right after like this如果结构是相同的,那么该变量中的数据将存储在架构中,那么您只需调用方法
.save()
,您可以像这样调用该方法
newFil(userData)
.save()
Now mongoose will store a new object with film Schema into the database you have connected at the top.现在 mongoose 会将一个带有 film Schema 的新对象存储到您在顶部连接的数据库中。 Keep in mind that, if you don't have a collection named film mongoDB will create one collection named films (the plural, always) and store the Schema there.
请记住,如果您没有名为film 的集合,mongoDB 将创建一个名为films (复数,始终)的集合并将架构存储在那里。
After saving you can res.redirect()
to "/" or render another page, that's up to you.保存后你可以
res.redirect()
到 "/" 或渲染另一个页面,这取决于你。
You have posted to url users/submit
but i don't see any API for users/submit
.您已发布到 url
users/submit
但我没有看到users/submit
任何 API。 You have said to use users for /users
urls but have you defined the /submit
within /users
?您曾说过将用户用于
/users
网址,但您是否在/users
定义了/submit
?
You could go through this Routing in expressjs您可以在 expressjs 中通过此路由
Inside your app.post
function you should have something like this:在你的
app.post
函数中,你应该有这样的东西:
let MongoClient = require('mongodb').MongoClient;
let connectionUrl = "mongodb://localhost:27017/";
// or
// let connectionUrl = "mongodb+srv://<username>:<password>@<your-cluster-url>/test?retryWrites=true&w=majority";
// creating the message object
let obj = {"text" : "Something"};
console.log("OBJ: " + obj);
MongoClient.connect(connectionUrl, function(err, client) {
if (err) throw err;
console.log("Connected correctly to server");
// if database and collection do not exist they are created
var db = client.db('YourDatabase')
db.collection("YourCollection").insertOne(obj, function(err, res) {
if (err) throw err;
console.log("1 message inserted");
client.close();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.