【问题标题】:Cannot search for all three properties on mongoDB无法在 mongoDB 上搜索所有三个属性
【发布时间】:2021-03-12 17:47:03
【问题描述】:

这是我在这里的第一篇文章。 在输入字符串或数字(姓名或姓氏或年龄)上键入时,我想在数据库中找到它(如果它们存在)。如果我键入一个字符串,它将在数据库中搜索该字符串(namesurname)。如果我输入将在数据库中搜索 age 属性的数字。

用户界面图片: UI picture

Input 具有将值转发到后端的 onChange 函数。 const 项是我转发到后端的字符串。

动作图:Action

当我在后端收到固定词时,我的搜索效果不佳。 在前面,当我输入一个数字时,他会搜索一个有这个数字的年龄,这没关系。 但是当我输入单词时搜索不起作用。

如果(在后端)我评论号码搜索它定期搜索姓名。

猫鼬模式图片:Model

怎么了?

后台图片:Backend

【问题讨论】:

    标签: node.js reactjs mongodb express redux


    【解决方案1】:

    当您从前端检查中获取数字或字符串的值时?如果字符串查找字段名称和姓氏,如果数字查找年龄。为 OR 条件创建一个数组,并根据输入(字符串或数字)将对象推送到该数组中,并将该数组传递给 OR。

    【讨论】:

    • 前端的值是一个字符串。在后端,我尝试将字符串转换为数字(用于数字字段)并且查询的结果是相同的。
    【解决方案2】:

    我认为这是因为您一直将String 用于Number 字段。如果根据输入的类型动态创建查询,则可以获得正确的结果。

    例子:

    const anyWorOrNum = req.params.x;
    
    // Check if anyWorOrNum is a number
    const isNumber = false;
    
    let anyNum = null;
    
    try {
        
        anyNum = Number(anyWorOrNum); // Trying to convert string into number.
    
        isNumber = true; // it's a number!
    
    } catch (err) {
    
        isNumber = false; // it's not a number!
    
    }
    
    const query = {};
    
    // If the input is number, just create a basic query that
    // only contains age search
    if (isNumber) {
    
       query.age = anyNum;
    
    } else {
    
       // Query now needs a $or operation to search in name and surname.
       query.$or = [{name: anyWorOrNum, surname: anyWorOrNum}];
    
    }
    
    // Use or array in find query
    
    const users = await userModel.find(query).exec();
    
    // Rest is same
    ..
    ..
    

    【讨论】:

    • 我以不同的方式检查类型: const checkType = !isNaN(parseInt(anyWordOrNum, 10));之后使用 if/else 来检查 if true find number else find string。你给我主意。谢谢
    • 有几种方法可以做到这一点。我很乐意为您提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2014-10-18
    • 1970-01-01
    相关资源
    最近更新 更多