刚开始使用node,express和mongodb(mongoose),这就是我想要做的事情:
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);
});
});
在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 } ]
如何将该对象传回search.jade,以便我可以在页面上显示它?
我知道我可以做res.render('search', {doc: doc});
但是当它被渲染时,页面已经被显示了..我是否必须以某种方式改变路线?
答案 0 :(得分:1)
再次从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');
});
});
然后使用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.