我想使用多个参数来查找One,但结果出现错误.tempUser可以输入为用户名、邮箱、移动电话

这是代码

const tempUser = req.body.input;
const user = await User.findOne({
     $or:
         [
            {username : tempUser},
            {mobilePhone : tempUser},
            {email : tempUser}
         ]
})

以下是集合示例

{
        "_id": "6531357830074bf5dfacb2de",
        "username": "elsa",
        "email": "elsa@gmail.com",
        "role": 4,
        "mobilePhone": 81702333244,
        "password": "elsa1234frozen",
        "__v": 0
},

如果我输入tempUser作为移动电话(例如:81234567891),它将返回正确的集合,但如果我输入tempUser作为用户名或通过邮箱发送它,则会出错.然后我try 使用Promise以及It Error,错误提示findOne()不再需要回调

我期待着如果我输入用户名、邮箱和手机中的任何一个来归还Collection

推荐答案

您不能这样做,因为mobilePhone被定义为Number,因此Mongoose将始终try 将tempUser的值转换为Number,以便它可以执行相等判断.当你经过一只Stringmongoose 时,它会抛出一个:

对于模型"User",路径"mobilePhone"处的值"a string here"(类型string)转换为Number失败

相反,您可以做的只是判断传入的值是否为Number,并根据需要构造您的查询对象.

这样的事情会帮助你达到想要的结果:

const tempUser = req.body.input;
let query;
if (isNaN(tempUser)) {
    query = {$or: [{username : tempUser}, {email : tempUser}]}
}else{
   query = {mobilePhone : tempUser}
}
const user = await User.findOne(query);

或者,如果你喜欢的话,可以 Select 更简洁的Conditional (ternary) operator号班轮:

const tempUser = req.body.input;
const query = isNaN(tempUser) ? {$or: [{username : tempUser}, {email : tempUser}]} : {mobilePhone : tempUser};
const user = await User.findOne(query);

Node.js相关问答推荐

使用OpenAI API时遇到问题

在编译时强制不缩小类型范围

如何从谷歌云中部署的应用程序连接到mongoDB Atlas?

DynamoDB 分页数据检索

在mongoose虚拟属性中处理异步操作

Docker node_modules 文件夹上的 React 应用程序不可用

suppress AWS SDK v2 弃用消息

使用正则表达式查找文档,但输入是数组

使用 Forms API 进行批量更新时生成 itemId

如何让 vscode 假设一个 node.js 上下文,以便它不假设 `fetch` 存在?

错误:无法检测到网络(event="noNetwork",code=NETWORK_ERROR,version=providers/5.6.8)

带权限的机密 Rest-Api - 总是 403 - 我做错了什么?

为什么我在生产环境中 deproy Next.js 示例项目时 CSS 不起作用?

yarn.lock 和 npm 的 package-lock 有什么区别?

node/express:使用 Forever 连续运行脚本时设置 NODE_ENV

TypeError:winston.Logger 不是带有winston 和morgan 的构造函数

使用 NodeJS 将新对象附加到 DynamoDB 中的 JSON 数组

nodejs:Ajax 与 Socket.IO,优缺点

使用 Node.js 我得到错误:EISDIR,读取

如何判断MongoDB本机nodejs驱动程序中是否存在集合?