【问题标题】:MongoDB insertion is giving schema validation errorMongoDB 插入给出模式验证错误
【发布时间】:2020-07-25 01:27:15
【问题描述】:

我是MongoDB 的新手,我已经写了我的schema validation 但我无法insert 数据给我schema validation error,代码如下所示,任何帮助将不胜感激。

验证者:

    db.createCollection("kartCollection", {
     validator: {
       $jsonSchema: {
         bsonType: "object",
         required: [ "uid", "items" ],
         properties: {
            uid: {
               bsonType: "number",
               description: "holds user id"
            },
            items: {
               bsonType: "object",
               required: [ "itemid","qty","qty_type","cost","currency" ],
               properties: {
                  itemid: {
                    bsonType: "number",
                     description: "holds items id"
                  },
                  qty: {
                     bsonType: "number",
                     "description": "holds quantity of item"
                  },
                  qty_type: {
                     bsonType: "string",
                     "description": "holds quantity type like l,kl,kg gm,pcs"
                  },
                  cost: {
                     bsonType: "number",
                     "description": "holds cost of the selected item for quiker fetch"
                  },
                  currency: {
                     bsonType: "string",
                     "description": "holds currency of the item sold in "
                  }
               }
            }
         }
      }
   }
});

db.kartCollection.insert({uid:'1',items:{{itemid:'1',qty:'1',qty_type:'kg',cost:'20',currency:'INR'}}});

错误

WriteResult({
            "nInserted" : 0,
            "writeError" : {
                    "code" : 121,
                    "errmsg" : "Document failed validation"
            }
    })

【问题讨论】:

    标签: mongodb validation schema


    【解决方案1】:

    尝试插入这个

    db.kartCollection.insert({uid:1,items:{ itemid:1,qty:1,qty_type:'kg',cost:20,currency:'INR'} }); 
    

    您的 uid、itemid、qty、cost 是 Number 类型,在上面的脚本中,您尝试插入字符串数据。 items 也是 object 类型的。

    【讨论】:

      猜你喜欢
      • 2020-12-20
      • 1970-01-01
      • 2017-08-18
      • 2017-04-09
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      相关资源
      最近更新 更多