MongoError:由于正则表达式模式,文档验证失败?

问题描述 投票:0回答:1

当我尝试在表单中的电话字段上应用正则表达式验证时,我收到“MongoError:文档验证失败”:

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 true e-mail "
          },

   Phone: {
           bsonType: "string",
           pattern:"^(0|\+33)[1-9]([-. ]?[0-9]{2}){4}$",
           description: "Phone must be a 10 digits french phone number, eventually using 33 format"
        },

然后我尝试像这样插入一个文档:

var db = client.db("dbName");
var testObj = {Email: "[email protected]", Phone: "+33606060606"};

db.collection("customers").insertOne(testObj, function(err, res) {
etc.});

==>失败了。

如果我删除电话字符串:

var db = client.db("dbName");
var testObj = {Email: "[email protected]"};

db.collection("customers").insertOne(testObj, function(err, res) {
etc.});

==>有效。

如果我在创建'customers'集合时删除正则表达式模式,它就可以工作。

我已经尝试了几个正则表达式/示例都在Javascript测试人员的在线正则表达式验证..所有失败.. :-(

感谢您对此的帮助,祝大家一切顺利!

node.js mongodb
1个回答
0
投票

这里的关键是正则表达式模式,你需要在这里加倍反斜杠

    pattern: "^(0|\\+33)[1-9]([-. ]?[0-9]{2}){4}$"

注意:我不确定如何更新现有的验证器,因此我删除了customers集合并使用正确的验证器模式重新创建

© www.soinside.com 2019 - 2024. All rights reserved.