通过表单输入和pug模板渲染器从Mongodb中检索数据

时间:2016-09-07 08:21:17

标签: javascript node.js mongodb mongoose pug

我目前遇到以下问题: 我无法从我的mongoDB中检索任何数据并将其显示在客户端或仅在其他路​​径上显示。我曾经使用过几次尝试,例如:

app.get('/output', function(req, res){
  Users.find(function (err, users){
    res.render('help', {users: users});
  });
});

然而,这结束于'用户未定义'。 当使用mongo shell并查询' show collections'时,我找到了'用户'使用表单输入中的数据进行收集。

如果有人可以向我解释如何根据以下代码检索数据并显示在' index.pug'中,我将非常感激。喜欢#{users.firstName}。

App.js代码:

var express = require('express');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');


app.get('/', function (req, res) {
  res.render('index', function(err, html) {
    res.send(html);
  });
});

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

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.use(express.static(__dirname + '/public'));

mongoose.connect('mongodb://localhost/myexpressapp');

var Schema = new mongoose.Schema({
  _id : String,
  firstName : String,
  lastName : String,
  City : String,
  Country : String
});

var user = mongoose.model('user', Schema);

app.post('/send', function(req, res){
  new user({
    _id: req.body.email,
    firstName: req.body.firstName,
    lastName: req.body.lastName,
    City: req.body.city,
    Country: req.body.country
  }).save(function(err, doc){
      if(err) res.json(err);
      else res.send('Successfully inserted');
  });
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
}); 

index.pug代码:

doctype html
html(lang='en')
  head
    meta(charset='utf-8')
    meta(http-equiv='X-UA-Compatible', content='IE=edge')
    meta(name='viewport', content='width=device-width, initial-scale=1')
    // The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags
    // Bootstrap
    link(href='css/bootstrap.min.css', rel='stylesheet')
    // HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries
    // WARNING: Respond.js doesn't work if you view the page via file://
    //if lt IE 9
      script(src='https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js')
      script(src='https://oss.maxcdn.com/respond/1.4.2/respond.min.js')
  body
  form(action='/send' method='POST')
    | Email:
    br
    input(type='text', name='email', value='#{user.firstName}')
    br
    | First Name:
    br
    input(type='text', name='firstName', value='')
    br
    | Last Name:
    br
    input(type='text', name='lastName', value='')
    br
    | City:
    br
    input(type='text', name='city', value='')
    br
    | Country:
    br
    input(type='text', name='country', value='')
    br
    input(type='submit', value='Submit')

    // jQuery (necessary for Bootstrap's JavaScript plugins)
    script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js')
    // Include all compiled plugins (below), or include individual files as needed
    script(src='js/bootstrap.min.js')

2 个答案:

答案 0 :(得分:1)

您必须使用您定义为模型user

var user = mongoose.model('user', Schema);

所以find的正确用法是:

user.find(...)

如果您想使用Users.find,那么您应该声明模型var Users = mongoose.model('user', Schema);

答案 1 :(得分:0)

一旦你拒绝放弃,奇迹就会发生。我想通了,万一有人坚持这个,这是工作代码:

app.js

class TestForm(Form):
    test_select = SelectField("Test", coerce=int)

@app.route("/test")
def view_function():
    form = TestForm()
    form.test_select.choices = [(0, "test0"), (1, "test1")]
    form.test_select.default = 1
    form.process()

index.pug

app.get('/retrieve', function(req, res){
    post.find({}, function(err, docs){
        if(err) res.json(err);
        else    res.render('retrieve', {posts: docs});
    });
});