如何在Express项目中实现视图间MongoDB文档数据传递?
Got it, let's break this down step by step. The key here is to use URL parameters to pass the unique ID of each document from the root list to the /view route, then fetch the full document in that route to display its content. Here's how to implement it with Express and Express Handlebars:
1. Update Your Root Route (/) to Fetch Documents
First, in your index.js, make sure you're fetching all the documents from MongoDB and passing them to your root view. Assuming you're using Mongoose (a common choice with Express), it might look like this:
var express = require('express'); var exphbs = require('express-handlebars'); var mongoose = require('mongoose'); // Add this if you haven't already var app = express(); // Set up Handlebars as your view engine app.engine('handlebars', exphbs({ defaultLayout: 'main' })); app.set('view engine', 'handlebars'); // Connect to your MongoDB database (replace with your connection string) mongoose.connect('mongodb://localhost:27017/your-database-name', { useNewUrlParser: true, useUnifiedTopology: true }); // Define your document schema/model (adjust fields to match your data) const Document = mongoose.model('Document', { date: Date, content: String, // Add any other fields you store in your documents }); // Root route: fetch documents and render the list view app.get('/', async (req, res) => { try { // Fetch all documents (add sorting/filters here if needed) const documents = await Document.find().sort({ date: -1 }); // Pass the documents array to your index view res.render('index', { documents }); } catch (err) { console.error(err); res.status(500).send('Failed to load documents'); } });
2. Render the Preview List in Your Index Handlebars Template
In views/index.handlebars, loop through the documents to create clickable list items that link to the /view route with each document's unique ID:
<ul class="document-list"> {{#each documents}} <li> <a href="/view/{{this._id}}"> {{this.date.toLocaleDateString()}} - {{this.content.substring(0, 100)}}... </a> </li> {{/each}} </ul>
{{this._id}}: Uses MongoDB's default unique identifier for each document (swap this with your own custom ID field if you have one).substring(0,100): Shows the first 100 characters of your content as a preview.toLocaleDateString(): Formats the date into a human-readable format (adjust this to match your preferred date style).
3. Create the /view Route to Fetch the Full Document
Back in index.js, add a route that accepts the document ID as a URL parameter, fetches the full document, and passes it to your detail view:
// View route: fetch a single document by ID and render full content app.get('/view/:docId', async (req, res) => { try { // Grab the document ID from the URL parameter const docId = req.params.docId; // Fetch the full document using its ID const document = await Document.findById(docId); if (!document) { // If no document matches the ID, send a 404 error return res.status(404).send('Document not found'); } // Pass the full document to your view template res.render('view', { document }); } catch (err) { console.error(err); res.status(500).send('Failed to load document'); } });
4. Display Full Content in the View Handlebars Template
Create views/view.handlebars to show the complete details of the document:
<div class="document-detail"> <h2>Document from {{document.date.toLocaleDateString()}}</h2> <p>{{document.content}}</p> <!-- Add any other fields from your document here --> <a href="/">← Back to document list</a> </div>
Quick Notes:
- If you're using the native MongoDB driver instead of Mongoose, replace
find()andfindById()with the equivalent native methods (likecollection.find()andcollection.findOne({ _id: ObjectId(docId) })). - Always handle errors (like invalid IDs or database connection issues) to keep your app stable.
- URL parameters are the cleanest way to handle this use case—avoid using session storage or hidden form data unless absolutely necessary.
内容的提问来源于stack exchange,提问作者brienna

