如何将数据从mongodb显示到jade / pug,nodejs

时间:2018-04-06 17:30:57

标签: node.js mongodb pug

我试图从mongodb获得一个简单的获取数据(所有年份/不同年份)并将其显示在一个选择下拉列表中,如图所示。

pie

我已经搜索并搜索了解决方案,但我要么得不到它,要么它不是我需要的东西,用我正在使用的东西写的。目前,此链接trying to display data in jade from mongodb可能是我想要的最具体的链接。但即使按照这个例子,我仍然无法将我的可变国家传递给玉石。后来,我计划使用列表中的年份作为变量来使用ajax查询mongodb。

这就是我到目前为止,请告诉我我做错了什么或为什么它没有按预期工作。

Country.js(模特)

var mongoose = require('mongoose');

var countrySchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {
        type: String,
        required: true
    },
    year: { 
        type: Number, 
        required: true
    },
    nominalGDP: Number,
    ...
    ...
});

var Country = mongoose.model('Country', countrySchema);

//****outputs to console, all the data I have****
Country.find(function (err, countries){
  console.log(countries);
});

// make this available to our users in our Node applications
module.exports = Country;

fetchCountries.js(Controller)

var Country = require('../models/country')
var express = require('express')
router = express.Router()


router.route('/')
.get( (req, res) => {
    Country.find({}, (err, countries) => {
      if (err)
        res.send(err)

      //***Does not output here***  
      console.log(countries);
      res.render('layout', {title: 'country list', countries: countries})
    });
  });

module.exports = router;

app.js

var express, path, favicon, logger, cookieParser, ... routes such as /index 
and /template, var app = express();

//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'mongodb://user, pass';
mongoose.connect(mongoDB, {
  useMongoClient: true
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/template', template);


//var Country = require('../models/country');

app.get('/', function(req, res){
  Country.find(function (err, countries){
    res.render('layout', {countries: countries});
  });    
});
module.exports = app;

layout.jade(view)

 ul List
        if countries
          each country in countries
            li #{country.year}

它位于localhost:3000 /,其中' /'是主页。我使用的是Mongodb / mongoose,node js,expressjs和jade / pug。

编辑:更新了fetchCountries控制器 编辑2:添加了app.js并更新了console.log输出的位置(在模型中)

0 个答案:

没有答案