Just starting out with node, express and mongodb (mongoose) and this is what I am trying to do:
刚开始使用node,express和mongodb(mongoose),这就是我想要做的:
- get parameters from jade file back to index.js via form ✔
- query the result in index.js ✔
- and then return the result back to jade and display it ✖
通过表单✔从jade文件获取参数返回index.js
在index.js中查询结果✔
然后将结果返回给jade并显示它✖
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:
在console.log(doc)中我得到一个json对象:
[ { _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?
如何将该对象传递回search.jade以便我可以在页面上显示它?
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?
我知道我可以做res.render('search',{doc:doc});但是当它被渲染时,页面已经被显示了..我是否必须以某种方式改变路线?
1 个解决方案
#1
1
Render the search.jade once again from searchByTitle.
再次从searchByTitle渲染search.jade。
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.
然后使用search.jade中的doc。
form(action='/searchByTitle', method='get')
input(type='text' name ='docTitle' placeholder='Title')
input(type="submit" value = 'submit')
if(doc)
//render the doc.
#1
1
Render the search.jade once again from searchByTitle.
再次从searchByTitle渲染search.jade。
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.
然后使用search.jade中的doc。
form(action='/searchByTitle', method='get')
input(type='text' name ='docTitle' placeholder='Title')
input(type="submit" value = 'submit')
if(doc)
//render the doc.