Node JS - Express - 如何在本地主机浏览器中搜索mongoDB object_id?

时间:2016-12-09 14:34:08

标签: javascript node.js express ejs

如何在浏览器中搜索object_id?有任何想法吗?我试过localhost:3000 / objectsearch?objectid = 58499f5ed0055acc431a99f0 但这只是提示"请输入一个objectID号并且不会重定向我"查看。 如果有人看到解决方案让我知道,谢谢

   **objectSearch.js**

var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var objectID = require('mongodb')
var url = 'mongodb://localhost:27017/WishList';



router.get('/', function (req, res) { //http://localhost:3000/objectSearch
    var _id = req.query.objectId;

    if (!_id || !parseInt(_id)) {
        res.render('error', {message: "Please enter an Buyer Identification Number", error: {status: "", stack: ""}});
    } else {
        mongoClient.connect(url, function (err, db) {
            if (err) {
                res.render('error', {message: "Failed to connect", error: {status: "", stack: ""}});
            } else {
                var WishListDB = db.collection('orders');
                WishListDB.find({_id: mongodb.ObjectID(_id)}).toArray(function (err, result) {
                    if (err || !result || result.length == 0) {
                        res.render('error', {
                            message: "No order found with that ID number",
                            error: {status: "", stack: ""}
                        });
                    } else {
                        res.render('objectSearch', {
                            objectSearch: result[0],
                            title: result[0]
                        })
                    }

                });

            }

        })
    }

});

module.exports = router;



**objectSeach.ejs**

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%=objectSearch.name.f %></p>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

i查询字符串的objectid字母为小写,但您的路由器期待objectId,您可以将路由器中的req.query.objectId更改为{{1}或者将浏览器中req.query.objectid的查询字符串更改为objectid