Nodejs Express 使用表单中的数据查询 mongolab 以获取单个条目

Nodejs Express query mongolab for a single entry using data from a form

我是 Nodejs 新手,我正在尝试使用表单条目中的数据在我的 mongolab 数据库中搜索条目(我知道存在)。这是我的代码:

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var path = require('path');
const MongoClient = require('mongodb').MongoClient;

var app = express();
app.set('view engine', 'ejs')
const port = 3000;

MongoClient.connect('mongodb://<user>:<password>@ds111882.mlab.com:11882/serene-brushlands-55292-db', function(err, database) {
    if(err) return console.log(err);
    db = database
    app.listen(port, function() {
    console.log('Server started at port:'+port);
    });
});

// var urlencodedParser = bodyParser.urlencoded({ extended:false });
app.use(bodyParser.urlencoded({extended:false}));
app.get('/', function(req, res) {
    res.sendFile(__dirname+'/index.html');
});

app.all('/addUser', function(req, res) {
    res.render('addUser');
    db.collection('users').save(req.body, function(err, result) {
        if (err) return console.log(err);
        console.log('saved to database');
    })
    console.log(req.body);
});


app.get('/outputAll', function(req, res) {
    db.collection('users').find().toArray(function (err, result) {
    if (err) return console.log(err);
    res.render('outputall', {users:result});
    });
});

app.get('/Search', function(req, res) {
    res.render('search');
    var query = {}
    console.log(req.body);
    if (req.body.username)
    {
    console.log("true");
    query.username = req.body.username;
    }
    db.collection('users').find({query}).toArray(function(err, result) {
    if (err) return console.log(err);
    console.log(1);
    });
});

search 部分就是为了完成这个 objective。但我不确定如何从我的输入表单中收集查询并将其传递给 this app.get 并将其传递给搜索它的数据库。这是 Search ejs 文件:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MY APP</title>
</head>
<body>
    <div style="margin: 0 auto;width: 500px;">
    <form action="/Search" method="GET" style="margin: 0 auto; width: 200px; margin-top: 100px;">
        <input type="text" placeholder="Search" name="username"  style="margin: 20px auto; font-size: 50px;">
        <!-- <input type="file" name="picture"> -->
        <button type="submit"  style="margin: 20px auto; font-size: 50px;">Submit</button>
    </form>
    </div>
</body>
</html>

当我 运行 时控制台上的输出是:

Server started at port:3000

{}

[]

{}

[]

我原以为 {}form 数据,[] 是在数据库中搜索查询的结果。 请帮忙!

----------------编辑-----------------

将表单方法更改为 post 后我收到的响应是:

Request body  = undefined
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]
Request body  = abc
[ { _id: 59384e971f8bc03d4ef35486 },
  { _id: 59385153304b40406d49ad28 },
  { _id: 5938519c58358a40e55cded8 },
  { _id: 593889193448616054a95b0d },
  { _id: 59388945b268a0607bce2e9c },
  { _id: 5938894bb268a0607bce2e9d,
    username: 'asfj',
    specialty: 'lkjsf',
    address: 'lkjsdf' },
  { _id: 59388ae40d294f6168c55ccf },
  { _id: 59388ddeba074c630a1a8861 },
  { _id: 5938922a9f549f667c9f7a91 },
  { _id: 5938c29c453e40053965e9eb },
  { _id: 5938c2f9453e40053965e9ec,
    username: 'abc',
    specialty: 'dsfsaddfjk',
    address: 'oidjfioa' },
  { _id: 5938c327453e40053965e9ed } ]

我已将 add.get('Search',fn) 更改为:

app.all('/Search', function(req, res) {
    res.render('search');
    db.collection('users').find().toArray(function(err, result) {
    if (err) return console.log(err);
    var query = {}
    console.log("Request body  = "+req.body.username);
    // if (req.body.username)
    // {
    //     console.log(req.body);
    //     query.username = req.body.username;
    // }

    console.log(result);
    });
});

您提出的 /Search 请求使用的是 GET 请求,而不是 POST。如果你想通过请求主体访问表单数据,我建议你使用 POST 方法或者访问 GET 方法的 url 参数。

收到数据后,您可以通过创建一个对象来为查询格式化它。

在 mongoose 中,您应该通过将对象作为参数发送来在数据库中查找文档。 例如,如果您要在数据库中查找姓名为 john 的人,您可以使用

db.collection('users').find({name: 'John'}).then(function(resp){}).catch(function(err){})

{name: 'John'} 是您的 javascript 对象猫鼬将在执行查询时使用

既然你说你是新手,那么学习这种称为 promises 的模式很有用。