NodeJS(express)我如何完成这个.js文件和.ejs文件来查询浏览器中的objectiD?

时间:2016-12-09 02:04:49

标签: javascript node.js mongodb express

我想要实现的是从我的mongoDB查询objectID到我的nodeJS然后通过我的本地主机检索它 http://localhost:3000/objectSearch?objectid=

我谷歌一切,我只是想不出来。如果有人会完成这个例子,那么我可以看看它是如何工作的,谢谢! :d

**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 (err, db) {
        if (err) {
            console.log("unable to connect to server", err);
        } else {
            console.log("Connect to server");
            var collection = db.collection('orders');
            var _id = req.query.id
            collection.findOne({_id: mongodb.ObjectID(_id)}, function (err, result) {
                if (err || !result) {
                    res.render('error', {error: "No records found with that id"});
                } else {
                    res.render(
                        'objectSearch',
                        {
                            objectSearch: result,
                            title: result
                        })
                }
            })
        }
    })

    module.exports = router;

ObjectSearch.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)

您在网址上的参数不是id,而是objectid,因此您的代码行应为:

req.query.objectid