You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js环境下如何将MongoDB数据展示到Jade/Pug下拉选择框

Solution: Fetch MongoDB Year Data & Render in Jade Dropdown

Hey there! Let's walk through how to get your MongoDB year data (both full and distinct values) into a Jade dropdown, and fix that variable-passing issue you're hitting. I'll assume you're using Node.js + Express with MongoDB (either native driver or Mongoose, since that's the most common stack paired with Jade).

Step 1: Backend - Fetch Data from MongoDB & Pass to Jade

First, we need to query MongoDB for the year data, then pass it to your Jade template when rendering.

If you're using Mongoose, here's how to get distinct years and pass them to your template:

// In your Express route file (e.g., routes/index.js)
const YearModel = require('../models/your-model'); // Import your Mongoose model

router.get('/', async (req, res) => {
  try {
    // Get distinct years from MongoDB
    const distinctYears = await YearModel.distinct('year');
    // Optional: Sort years in ascending order
    distinctYears.sort((a, b) => a - b);

    // Pass the years to your Jade template
    res.render('your-template', { 
      title: 'Year Selector',
      years: distinctYears // This variable will be accessible in Jade
    });
  } catch (err) {
    console.error('Error fetching years:', err);
    res.status(500).send('Failed to load year data');
  }
});

Option 2: Using Native MongoDB Driver

If you're using the native driver, the approach is similar:

const { MongoClient } = require('mongodb');

router.get('/', async (req, res) => {
  const client = new MongoClient('your-mongodb-connection-string');
  try {
    await client.connect();
    const db = client.db('your-db-name');
    const collection = db.collection('your-collection-name');

    // Get distinct years
    const distinctYears = await collection.distinct('year');
    distinctYears.sort((a, b) => a - b);

    res.render('your-template', { years: distinctYears });
  } catch (err) {
    console.error(err);
    res.status(500).send('Error loading years');
  } finally {
    await client.close();
  }
});

Step 2: Fix the "Variable Not Reaching Jade" Issue

From your description, it sounds like the variable (you mentioned countries in the example, but we're using years here) isn't making it to Jade. Here's how to debug and fix this:

  • Double-check variable names: Make sure the key you pass in res.render() (e.g., years) matches exactly what you use in Jade. Typos are the #1 culprit here!
  • Verify data exists: Add a console.log(distinctYears) right before res.render() to confirm MongoDB is returning data. If it's empty, your query might target the wrong field or collection.
  • Check async handling: If you're not using async/await or callbacks correctly, the template might render before the MongoDB query finishes. Always wait for the query to resolve before calling res.render().

Step 3: Render the Dropdown in Jade

Now that the years variable is available in Jade, loop through it to build your dropdown:

// In your-template.jade
h1 Select a Year
form
  select(name="selectedYear")
    option(value="") -- Choose a Year --
    each year in years
      option(value=year)= year

Bonus: Fetching Full (Non-Distinct) Year Data

If you need all year entries (including duplicates), replace the distinct query with a regular find that selects only the year field:

// Mongoose example
const allYearDocs = await YearModel.find().select('year').lean();
// Extract just the year values from the documents
const yearValues = allYearDocs.map(item => item.year);
res.render('your-template', { years: yearValues });

Quick Troubleshooting Tips

  • Year data type: If your years are stored as strings instead of numbers, sorting might not work as expected. Convert them to numbers with distinctYears.map(year => parseInt(year)).sort(...).
  • Jade vs Pug: If you're using the latest version, it's now called Pug—make sure your file extension is .pug or your Express app is configured to use Jade.

内容的提问来源于stack exchange,提问作者NotSure

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:34:10