简体   繁体   English

如何从数据库中的标签“ a”中插入值以属性href

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

how can I pass an ID to href? 如何将ID传递给href? I return it via req.params, it returns undefined. 我通过req.params返回它,它返回未定义。 I need to get the id from this url to use the findOne method to access the data in the database. 我需要从此URL获取ID,以使用findOne方法访问数据库中的数据。

I'm was tried find this in pug documentation, but nothing. 我试过在哈巴狗文档中找到它,但是什么也没有。 I know, mb this question is stupid, but idk how to do it. 我知道,mb这个问题很愚蠢,但是idk怎么做。 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 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: 如果有人遇到这种情况:U需要在循环中初始化var,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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