您正在提供一个值...这是一个有效的Map 定义:
await User.create({
modules: {
example: {} // <-- this is a valid. Key is `example` value is {}
}
})
至于Map 没有验证。 Map 确实验证 values 只是因为键始终是字符串。考虑这个架构:
var AuthorSchema = new Schema({
books: {
type: Map,
of: { type: Number },
default: { "first book": 100 }, // <-- set default values
required: true // <-- set required
}
})
// after mongoose.model('Author', AuthorSchema) etc ....
var author1 = new Author({ books: { 'book one': 200 } })
author1.save() // <-- On save this works
var author2 = new Author({ books: { 'book one': "foo" } })
author2.save() // <-- This fails validation with "Cast to number failed ..."
var author1 = new Author()
author1.save() // <-- default would set values and that would pass the `required` validation
如果您想要求地图,请确保您没有默认值等。
您还可以查看map tests @ github 以获得更多信息
在这些测试中,您还可以看到如何制作复杂的嵌套地图:
var AuthorSchema = new Schema({
pages: {
type: Map,
of: new mongoose.Schema({ // <-- just nest another schema
foo: { type: Number }, // <-- set your type, default, required etc
bar: { type: String, required: true } // <-- required!
}, { _id: false }),
default: {
'baz': {
foo: 100, bar: 'moo' // <-- set your defaults
}
}
}
})
这将按预期保存:
{
"_id" : ObjectId("5cf1cf4b7f67711963e2406d"),
"pages" : {
"baz" : {
"foo" : 100,
"bar" : "moo"
}
}
}
试图保存它会失败,因为bar 是必需的:
var author = new Author({
"pages" : {
"baz" : { "foo" : 1 } // <-- no bar!
}
});