首页 > 解决方案 > 如何在猫鼬中找到“按名称”

问题描述

我正在尝试使用特定名称获取数据库值。我想得到一个作者写的所有书。

这是我的代码,用于获取作者的名字并使用运算符搜索他在BookDB中编写的所有书籍,如Likemysql

//get books by author name
router.route('/authorName').get((req, res) => {
    let authorName = req.params.authorName; //how can i pass this value to below regex command
    BookDB.find({"firstName": /authorName/}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});

问题:如何传递authorName给 {"firstName": /authorName/}。我写的方式,设置不authorName正确。

标签: javascriptexpressmongoose

解决方案


我做了一些研究,发现$regex

//get books by author name
router.route('/authorName').get((req, res) => {
    let authorName = req.params.authorName;
    BookDB.find({firstName: {$regex: `${authorName}`}}, (err, books) => {
        if(err) throw err;
        res.status(200).send(books);
    });
});

authorName这将在数​​据BookDB库中找到包含此特定字符串的所有结果


推荐阅读