如何在插入或更新 MongoDB 前验证文档?
要验证文档,请使用验证的概念。以下为查询 −
> db.createCollection("demo356", {validator: { ... $and: [ {"FirstName": {$type: "string", $exists: true}} ] ... }}) { "ok" : 1 }
让我们创建一个包含文档的集合 −
> db.demo356.insertOne({"FirstName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5e568d49f8647eb59e5620c7") } > db.demo356.insertOne({"FirstName":909}); 2020-02-26T20:52:58.497+0530 E QUERY [js] WriteError: Document failed validation : WriteError({ "index" : 0, "code" : 121, "errmsg" : "Document failed validation", "op" : { "_id" : ObjectId("5e568d52f8647eb59e5620c8"), "FirstName" : 909 } }) WriteError@src/mongo/shell/bulk_api.js:461:48 Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49 Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13 Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21 DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9 @(shell):1:1
使用 find() 方法显示集合中的所有文档 −
> db.demo356.find();
这将生成以下输出 −
{ "_id" : ObjectId("5e568d49f8647eb59e5620c7"), "FirstName" : "Chris" }
广告