简体   繁体   中英

How to insert value from the database in tag “a” to attribute href

how can I pass an ID to href? I return it via req.params, it returns undefined. I need to get the id from this url to use the findOne method to access the data in the database.

I'm was tried find this in pug documentation, but nothing. I know, mb this question is stupid, but idk how to do it. Please help. Code:

my pug code:

  div(class = "container")
    for item in items
      div
        a(href='/routes/#{item._id}')= item.InputItemName //this is one of the many variations of my attempts

controller.js

const {ObjectID} = require('mongodb'); //get objectid method
router.get('/:itemId', async (req, res) =>{
    const client = req.app.client;
    const db = client.db('MyDB'); //cnn to db
    const collection = db.collection('items'); //cnn to collection items
    var req_id= req.params.itemId; 
    console.log(req_id); //undefined
    const item = await collection.findOne({ _id: ObjectID(req_id)}); //not working, coz req_id = undefined
    console.log(item);
    if(!item) return res.redirect('/');
    res.render('routes/views/item', {item}); 
});

I was solved this problem. If anyone bumps into that: U need to init var in loop, like this:

  div(class = "container")
    for item in items
      div
        img(src='firs.png', alt='image')
        - var url = item._id;
        a(href='/routes/' + url)=  item.InputItemName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM