MongoDB 模式驗證
模式驗證
預設情況下,MongoDB 具有靈活的模式。這意味著初始時沒有設定嚴格的模式驗證。
可以建立模式驗證規則,以確保集合中的所有文件都具有相似的結構。
模式驗證
MongoDB 支援 JSON Schema 驗證。 $jsonSchema
運算子允許我們定義文件結構。
示例
db.createCollection("posts", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [ "title", "body" ],
properties: {
title: {
bsonType: "string",
description: "Title of post - Required."
},
body: {
bsonType: "string",
description: "Body of post - Required."
},
category: {
bsonType: "string",
description: "Category of post - Optional."
},
likes: {
bsonType: "int",
description: "Post like count. Must be an integer - Optional."
},
tags: {
bsonType: ["string"],
description: "Must be an array of strings - Optional."
},
date: {
bsonType: "date",
description: "Must be a date - Optional."
}
}
}
}
})
自己動手試一試 »
這將建立當前資料庫中的 posts
集合,併為該集合指定 JSON Schema 驗證要求。