You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoError文档验证失败:手机号正则校验问题求助

Fixing MongoDB Document failed validation for Phone Number Regex

Hey there, let's dig into why your phone number validation is failing in MongoDB! The issue boils down to a common gotcha with JSON and regular expressions: escape characters.

What's Going Wrong?

When you defined the pattern for your Phone field, you used "^(0|\+33)[1-9]([-. ]?[0-9]{2}){4}$". But in JSON strings, a single backslash \ acts as an escape character. That means \+ gets parsed as just + by MongoDB, turning your regex into ^(0|+33)... — which is invalid regex syntax (the + quantifier can't follow a pipe | directly). This breaks the validation, even though the regex works in JavaScript testers (since JS uses regex literals that don't require double-escaping).

While you didn't hit it yet, your Email regex also has a small issue: the .[A-Z]{2,} part uses an unescaped ., which matches any character instead of a literal dot. We'll fix that too.

The Fix: Double-Escape Your Regex Special Characters

In JSON-based MongoDB schemas, you need to use two backslashes to represent a single backslash in your regex. Here's the corrected createCollection command:

db.createCollection("customers", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["Email", "Phone"],
      properties: {
        Email: {
          bsonType: "string",
          pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$",
          description: "E-mail must be a string and a valid email address"
        },
        Phone: {
          bsonType: "string",
          pattern: "^(0|\\+33)[1-9]([-. ]?[0-9]{2}){4}$",
          description: "Phone must be a 10-digit French phone number, optionally using the +33 format"
        }
      }
    }
  }
})

Key Changes:

  • For the phone number: \+ becomes \\+ — this ensures MongoDB sees the literal + in the regex instead of trying to interpret it as an escape sequence.
  • For the email: .[A-Z]{2,} becomes \\.[A-Z]{2,} — this makes the dot match only literal dots in the email domain.

Test It Out

Now when you run your insert command:

var db = client.db("dbName");
var testObj = {Email: "EMAIL@DOMAIN.COM", Phone: "+33606060606"};
db.collection("customers").insertOne(testObj, function(err, res) {
  // Your callback logic here
});

It should succeed without the Document failed validation error!

As an alternative, if you're using the MongoDB shell directly, you can use regex literals (like /^(0|\+33)[1-9]([-. ]?[0-9]{2}){4}$/) instead of string patterns — this avoids the need for double-escaping. But if you're defining the schema via JSON (e.g., in an application), the double-escaped string is the way to go.

内容的提问来源于stack exchange,提问作者Titetili

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:32:46