bobby bobby - 3 months ago 16
Node.js Question

Passing variables (server side / client side ) node js

Just starting out with node, express and mongodb (mongoose) and this is what I am trying to do:


  1. get parameters from jade file back to index.js via form ✔

  2. query the result in index.js ✔

  3. and then return the result back to jade and display it ✖



search.jade

form(action='/searchByTitle', method='get')
input(type='text' name ='docTitle' placeholder='Title')
input(type="submit" value = 'submit')


index.js

...
var Document = require('../models/document');
...

router.get('/search', function(req, res){
res.render('search');
});

router.get('/searchByTitle', function(req, res){

var title = req.param('docTitle');

Document.find({ title: title }, function(err, doc) {
if (err) throw err;
console.log(doc);
});
});


in
console.log(doc)
I get a json object:

[ { _id: 57b4725b3cd1c8a028a6f686,
title: 'title123',
category: 'category123',
author: 'Anne',
date: Thu Aug 25 2016 02:00:00 GMT+0200 (Central European Daylight Time),
version: 1,
file: 'test.txt',
__v: 0 } ]


How do I pass that object back to search.jade so that i can display it on a page?

I know I can do
res.render('search', {doc: doc});
but by the time it is rendered, page is already being shown.. Do I have to change the routes somehow?

passing values

Answer

Render the search.jade once again from searchByTitle.

router.get('/searchByTitle', function(req, res){

var title = req.param('docTitle');

Document.find({ title: title }, function(err, doc) {
    if (err) throw err;
      console.log(doc);
      res.locals.doc = doc;
      res.render('search');
    });         

});

Then use use the doc in search.jade.

form(action='/searchByTitle', method='get')
input(type='text' name ='docTitle' placeholder='Title')
input(type="submit" value = 'submit')
if(doc)
     //render the doc.