【问题标题】:How could i concatenate two strings in my search box in node js?如何在节点 js 的搜索框中连接两个字符串?
【发布时间】:2020-10-06 22:51:45
【问题描述】:

这是我的代码,我的搜索框仅在我输入名字或姓氏时搜索人,但如果我一起输入“名字姓氏”,我也希望它显示结果。 有人可以建议我应该在 collection.find({}) 中输入什么参数吗? 请帮忙!

function escapeRegExp(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
} 

async website(req, res) {
        if(req.query.search){
            const regEx = new RegExp(escapeRegExp(req.query.search), "gi");
            await Web.find( {$or: [{firstname: regEx}, {lastname: regEx}] }, function(err, web) {
                if(err)
                {
                    console.log(err);
                    res.send("error", "Oops, Something went wrong! Please try again.");
                }   
                else
                {
                    res.render("./web/webProfiles", { web });
                }   
            });
        }
}

【问题讨论】:

    标签: javascript node.js mongodb search search-engine


    【解决方案1】:
    await Web.aggregate([
     {
        "$group":{
             _id:"$_id",
             "full_name":{$first:{$concat:['$firstname',' ',"$lastname"]}},
             "firstname"{$first:"$firstname"},
             "lastname"{$first:"$firstname"},
         }
     },
     {$match:{$or: [{firstname: regEx}, {lastname: regEx},{full_name:regEx}] }}
    
    ]);
    
    you can check mongodb aggregation and concat. In Group function you can write what you want in your response.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-28
      • 2017-04-04
      • 2017-04-27
      • 2016-03-01
      • 1970-01-01
      • 2016-11-20
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多