如何使用express route param访问数据库对象

时间:2016-11-23 23:40:07

标签: javascript express

我正在尝试使用express.js从数据库查询中路由不同的无线电会话/剧集。我能够在快速路线中从URL中获取路线参数。但我不确定如何使用param查询数据库中的正确对象。

我可以通过将param硬编码到我的服务中来实现这一点,如下所示,在service.js中使用'title'变量。目前,我只知道如何将变量从express传递给视图。有没有办法将标题参数从我的快速路径传递给service.js文件?

Routes.js

'use strict';

const express = require('express');
const Sessions = require('../models/sessions')
const routes = express.Router();
const apiRoutes = express.Router();

apiRoutes.get('/sessions', (req, res) => {
  Sessions.find({}, (err, sessions) => {
    if(err) {
      return res.status(500).json({message: err.message});
    }
    res.json({sessions: sessions});
  })
});

routes.get('/', (req, res, next) => {
  return res.render('index', {title: 'Home'});
});


// I added this bit of code after realizing I needed to use mongoose to query the database. I'm still unsure how to pass the object to my javascript but I'm getting closer.
routes.get('/:title', function (req, res, next) {
  const title = req.params.title
  Sessions.find((err, sessions) => {
    if (err) return console.error(err);
    for (let i = 0; i < sessions.length; i++) {
      if (title === sessions[i].title.toLowerCase()) {
        res.render('session')
      }
    }
  })
})

module.exports = [routes, apiRoutes];

index.js

'use strict';
const express = require('express');
const app = express();
const [routes, apiRoutes] = require('./src/routes');

require('./src/database');
require('./src/seed');

app.use('/', express.static('public'));

app.set('view engine', 'pug');
app.set('views', __dirname + '/views');

app.use('/api', apiRoutes);
app.use('/', routes);

app.listen(process.env.PORT || 8082);

service.js

const root = window.location.origin;
const title = 'session 1'

function callService(){
  service(`${root}/api/sessions`)
    .then(retrieveSession)
    .catch(function(e) {
      console.log(e)
    });
}

function retrieveSession(data) {
  for (let i = 0; i < data.sessions.length; i++) {
    if(data.sessions[i].title.toLowerCase() === title) {
      return data.sessions[i];
    }
  }
}

function service(url) {
  return new Promise(function(res, rej) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', url);
    httpRequest.onreadystatechange = handleResponse;
    httpRequest.onerror = function(error) {
      rej(error)
    }
    httpRequest.send();

    function handleResponse() {
      if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
          var data = JSON.parse(httpRequest.responseText);
          res(data)
        } else {
          rej(this.statusText)
        }
      }
    };
  });
}

1 个答案:

答案 0 :(得分:0)

我可以通过mongoose将数据传递给视图,并使用以下代码段来实现所需的结果。

routes.get('/:title', function (req, res, next) { // Passes url param
  const title = req.params.title //stores url param in varaible
  Sessions.findOne({ 'title': title }, function (err, session) { // compares url param against my mongoose schema and queries the database for the desired object
    if (err) return handleError(err); // checks for errors
    res.render('session', {session: session}); // renders the page while passing the desired data.
  })
})