MongoDB $strLenCP报错:要求字符串参数却提示缺失的问题排查
错误原因
报错$strLenCP requires a string argument, found: missing的核心原因有两个:
- 你的MongoDB集合里存在部分文档没有
name字段,当$strLenCP尝试读取不存在的字段时,就会返回missing,触发参数类型错误。 - 部分文档的
name字段不是字符串类型(比如是数字、null、数组等),$strLenCP只能处理字符串,非字符串类型也会导致类似报错。
验证与解决方法
1. 先排查问题数据
执行以下查询,找出不符合要求的文档:
// 查找没有name字段的文档 await userModel.find({ name: { $exists: false } }); // 查找name字段不是字符串的文档 await userModel.find({ name: { $not: { $type: "string" } } });
2. 修改查询逻辑
根据你的需求选择处理方式:
方式一:过滤掉无name或非字符串的文档
直接在查询条件里先筛选出合法的文档,再判断长度:
let userData = await userModel.find({ name: { $exists: true, $type: "string" }, $expr: { $and: [ { $gte: [{ $strLenCP: "$name" }, 0] }, { $lte: [{ $strLenCP: "$name" }, 30] }, ], }, });
方式二:兼容无name的文档
用$ifNull把缺失的name字段替换为空字符串,避免报错:
let userData = await userModel.find({ $expr: { $and: [ { $gte: [{ $strLenCP: { $ifNull: ["$name", ""] } }, 0] }, { $lte: [{ $strLenCP: { $ifNull: ["$name", ""] } }, 30] }, ], }, });
内容的提问来源于stack exchange,提问作者Saha Technical
相关产品推荐
相关产品推荐

