Node.js与MongoDB中无法获取data-id问题求助
Hey there! Let's work through this data-id issue together—been there with my first Node/Mongo project, so I totally get the frustration 😊
First, make sure you're actually outputting the Mongo document's _id correctly in your index.pug file. Mongo uses _id (with an underscore) for its default document IDs, so your Pug code should look something like this:
each item in items .item(data-id=item._id) #{item.title}
After rendering, right-click the element in your browser and select "Inspect" to verify the data-id attribute has a real value. Sometimes a tiny Pug syntax mistake (like forgetting the equals sign, or misspelling item._id as item.id) can leave the attribute empty.
You’re using $(document).ready() which is good, but if your elements are dynamically rendered (pulled from the database and injected into the page), direct event binding might fail. Use event delegation instead—it works for elements that don’t exist yet when the page loads:
$(document).ready(function() { // Use event delegation to listen for clicks on .item elements $(document).on('click', '.item', function() { // Try two ways to get the ID: const idFromData = $(this).data('id'); // Uses jQuery's data() method const idFromAttr = $(this).attr('data-id'); // Gets the raw attribute string console.log('ID from data():', idFromData); console.log('ID from attr():', idFromAttr); // If idFromData is an ObjectID (not a string), convert it: const idString = typeof idFromData === 'object' ? idFromData.toString() : idFromData; console.log('Final ID string:', idString); }); });
The data() method sometimes parses values into objects (like Mongo’s ObjectID), so converting to a string with .toString() might be necessary if you need the raw ID string.
_id to the Template Check your index.js (backend code) to ensure you’re sending the full document (including _id) to Pug. For example, if you’re using Express and Mongoose:
app.get('/', async (req, res) => { try { // Make sure you're not excluding _id with a projection like '-_id' const items = await YourModel.find({}); console.log(items); // Check your backend console to confirm _id exists on each item res.render('index', { items }); } catch (err) { console.error(err); res.status(500).send('Failed to load items'); } });
If you added a projection like .find({}, '-_id'), you’re explicitly removing the _id field—remove that to keep the ID in your data.
- Did you include jQuery? If
$is undefined in your console, your$(document).ready()won’t run. Add this to your Pug’s<head>:script(src='https://code.jquery.com/jquery-3.7.1.min.js') - Typos are evil! Double-check you wrote
data-id(hyphenated) notdataIdordata_id, and that your variable names match between backend, Pug, and frontend JS.
If you still hit a wall, share snippets of your index.pug and index.js relevant code—I can help you spot the exact issue!
内容的提问来源于stack exchange,提问作者E0110

