我一直在尝试将数据保存到mongodb数据库,但我似乎无济于事。我遇到的第一个错误与req.body有关

当我单击提交按钮时,console.log(req.body)返回

[Object: null prototype] { name: 'John', priority: 'go to bed' }


而不是

{ name: 'John', priority: 'go to bed' }


其次,我不知道是否将数据正确保存到数据库中,因为我已经看到了很多不同的处理方式,这让我感到困惑

相关代码行

db.collection.insertOne(req.body);


和相关的错误:

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>

最佳答案

关于第一个错误,您应该添加这两行以将json数据作为请求对象,因为您正在json中发送数据

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


关于第二个查询:
在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();
      });
    });

关于javascript - 您如何使用mongodb native ,express和body-parser来发布请求并保存数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54667408/

10-09 23:50
查看更多