[英]How do you use mongodb native, express and body-parser to post request and save data?
I have been trying to save data to a mongodb database but nothing I do seems to work. 我一直在尝试将数据保存到mongodb数据库,但我做的一切似乎都没有用。 the first error i'm getting is related to the req.body
我得到的第一个错误与req.body
When I click the submit button, console.log(req.body)
returns 当我单击提交按钮时, console.log(req.body)
返回
[Object: null prototype] { name: 'John', priority: 'go to bed' }
rather than 而不是
{ name: 'John', priority: 'go to bed' }
Secondly, I don't know if I'm saving the data to the database correctly because I have seen so many different ways of doing it that I'm confused 其次,我不知道我是否正确地将数据保存到数据库中,因为我已经看到了很多不同的方法,我很困惑
The relevant line of code 相关的代码行
db.collection.insertOne(req.body);
and relevant error: 和相关的错误:
TypeError: db.createCollection is not a function
const express = require('express'); const app = express(); const bodyParser = require('body-parser'); var urlencodedParser = bodyParser.urlencoded({ extended: false }); const MongoClient = require('mongodb').MongoClient; // Connection URL const url = "mongodb://localhost:27017"; app.listen(7000); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }) app.post('/todo',urlencodedParser,function(req, res){ MongoClient.connect(url, { useNewUrlParser: true }, function(err,db){ if(err) throw err; console.log('Databese created!'); db.collection.insertOne(req.body); db.close(); }); console.log(req.body); });
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> I am an index page. <form class="" action="/todo" method="post"> <input type="text" name="name" placeholder="todo"> <input type="text" name="priority" placeholder="priority"> <button type="submit">Submit</button> </form> </body> </html>
Regarding first error , You should add this two line to get json data as a request object because you're sending data in json 关于第一个错误 ,你应该添加这两行来获取json数据作为请求对象,因为你在json中发送数据
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
Regarding second query: Inserting record in mongoDB 关于第二个查询:在mongoDB中插入记录
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
Your problem is that you don't specify to your MongoDB Instance which database you are using. 您的问题是您没有为MongoDB实例指定您正在使用的数据库。
const url = "mongodb://localhost:27017/myDataBaseName";
This should solve this out for you. 这应该为你解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.