所以我对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位整数。我也试过使用" date"和"时间戳"日期类型无济于事。
我的插入是:
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'数字'对于numAnimals,但也没有。
任何有用的想法或意见将不胜感激!
答案 0 :(得分:1)
您的验证需要" observationTimestamp"和" numAnimals"作为int和long类型。
因此,当插入关联的正确类型时。
像
这样的东西db.observations.insert([
{
"observationTimestamp" : NumberLong(Date.parse("Mon, 25 Dec 1995 12:34:56 GMT")),
"family" : "Sharks",
"species" : "Carcharodon carcharias",
"numAnimals" : NumberInt(3)
}
]);