所以我对 MongoDB 很陌生,当然,关于文档何时验证失败的反馈有点……没有信息。所以我希望任何人都能看到我犯的错误。
该模式相对简单并且有效:
db.createCollection("observations", {
autoIndexId : true,
validator : {
$jsonSchema: {
bsonType: "object",
required: [ "observationTimestamp", "family", "species", "numAnimals" ],
properties: {
observationTimestamp: {
bsonType: "long",
description: "Time that the animal(s) were observed. Use 'Date.parse()' syntax when inserting records. Required field. Example: 'Date.parse('Tue, 12 Dec 1995 16:17:18 GMT')'."
},
family: {
bsonType: "string",
description: "Vernacular name of group which species belongs to. Required field. Must be a string."
},
species: {
bsonType: "string",
description: "Scientific name of observed animal. Required field. Must be a string."
},
numAnimals: {
bsonType: "int",
minimum: 1,
description: "Number of animals observed. Required field. Must be an integer."
}
}
}
}
} );
我在这里使用“long”作为“Date.parse()”,因为我了解到它返回一个 64 位整数。我也尝试使用“日期”和“时间戳”日期类型无济于事。
我的插入是:
db.observations.insert([
{
"observationTimestamp" : Date.parse("Mon, 25 Dec 1995 12:34:56 GMT"),
"family" : "Sharks",
"species" : "Carcharodon carcharias",
"numAnimals" : 3
},
{
"observationTimestamp" : Date.parse("Tue, 12 Dec 1995 16:17:18 GMT"),
"family" : "Sharks",
"species" : "Carcharias taurus",
"numAnimals" : 4
}
]);
运行命令时给出的错误是通用的:
BulkWriteResult({
"writeErrors" : [
{
"index" : 0,
"code" : 121,
"errmsg" : "Document failed validation",
"op" : {
"_id" : ObjectId("5a5e4291aa4da4bdfe1a234c"),
"observationTimestamp" : 819894896000,
"family" : "Sharks",
"species" : "Carcharodon carcharias",
"numAnimals" : 3
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
这是使用 MongoDB 服务器版本 3.6。我在 Windows 10 平台上运行(如果这意味着什么)。
我唯一能想到的另一件事是将 bsonType 'number' 用于 numAnimals,但这也不起作用。
任何有用的想法或意见将不胜感激!