【问题标题】:Nodejs Express query mongolab for a single entry using data from a formNodejs Express 使用表单中的数据查询 mongolab 以获取单个条目
【发布时间】:2017-06-09 00:22:59
【问题描述】:

我是 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 部分旨在实现此目标。但我不确定如何从我的输入表单中收集查询并将其传递给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>

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

服务器启动于端口: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);
    });
});

【问题讨论】:

    标签: node.js mongodb forms express mlab


    【解决方案1】:

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

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

    【讨论】:

    • 我不知道如何为查询创建对象。你能详细说明一下吗?
    • 它只是普通的 javascript 对象。如果你问我如何查询,那么我需要知道你收到了什么数据。您走在正确的道路上,只需为其余字段执行您为用户名所做的操作。我想,一旦您收到数据,您就会很清楚。如果不能随意评论您的数据和您想要查询的内容。
    • 是的,它似乎更清楚了。我已经编辑了问题并添加了详细信息。
    • 目前还不清楚您希望查询的结果是什么以及架构中有哪些字段。我想你已经解决了你的问题。如果没有,请参考@necilAlbayrak 答案进行查询。
    【解决方案2】:

    在猫鼬中,您应该通过将对象作为参数发送来在您的数据库中找到文档。 例如,如果您正在数据库中寻找一个名为 john 的人,您可以使用

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2022-10-02
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多