2021/7/26
一、 mongoose验证
在创建集合规则时,可以设置当前字段的验证规则,验证失败就输入插入失败
- required: true ---- 必传字段
- minlength: 2 ----字符串最小长度为2
- maxlength: 20 ----字符串最大长度为20
- trim: true ---- 去除两边空格
- min: 2 ---- 数值最小值为2
- max: 20 ---- 数值最大值为20
- enum: [‘html’, ‘css’, ‘javascript’, ‘node.js’] —限制内容选择
- validate: 自定义验证器
const mongoose = require('mongoose');
//数据库连接
mongoose.connect('mongodb://localhost/plabck', {
useNewUrlParser: true ,
useUnifiedTopology: true
}).then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));
const postSchema = new mongoose.Schema({
title: {
type: String,
// 必选字段
required: [true, '缺少必选项 文章标题'],
// 字符串的最小长度
minlength: [2, '文章长度不能小于2'],
// 字符串的最大长度
maxlength: [5, '文章长度最大不能超过5'],
// 去除字符串两边的空格
trim: true
},
age: {
type: Number,
min: 18,
max: 100,
},
publishDate: {
type: Date,
// 默认值为当前时间
default: Date.now
},
category: {
type: String,
//枚举 列举(列举出当前字段可以传递的值)
enum:{
values: ['html', 'css', 'javascript', 'node.js'],
message: '分类名称不在固定范围内'
}
},
author: {
type: String,
validate: {
validator: v => {
/*
返回布尔值
true 验证成功
false 验证失败
v 要验证的值
*/
return v && v.length > 4
},
//自定义错误信息
message: '传入的值不符合验证规则'
}
}
});
在上述代码中有自定义的错误信息,但若平时的学习中没有考虑到这一方面,怎么办呢?-----我们可以通过create()的返回值来筛选出我们需要的具体错误信息
在这里插入代码片const Post = mongoose.model('Post', postSchema);
Post.create({title: 'web', author: 'bd', category: 'java'})
.then(result => console.log(result))
.catch(error => console.log(error);
可以根据循环语句筛选得到自己想要的数据
const Post = mongoose.model('Post', postSchema);
Post.create({title: 'web', author: 'bd', category: 'java'})
.then(result => console.log(result))
.catch(error => {
// 获取错误信息对象
const err = error.errors;
// 循环错误信息对象
for (var attr in err) {
// 循环错误信息打印到控制台中
console.log(err[attr]['message']);
}
});
若没有设置自定义报错信息
二、集合关联
通常不同集合的数据之间是有关系的 , 例如文章信息和用户信息存储在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联
- 使用id对集合进行关联
- 使用populate方法进行关联集合查询
const mongoose = require('mongoose');
//数据库连接
mongoose.connect('mongodb://localhost/plabck', {
useNewUrlParser: true ,
useUnifiedTopology: true
}).then(() => console.log('数据库连接成功'))
.catch(err => console.log('数据库连接失败', err));
//文章集合规则
const PostRule = new mongoose.Schema({
title: {
type: String,
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}
})
// 用户集合规则
const UserRule = new mongoose.Schema({
name: {
type: String,
required: true
}
})
// 创建集合
const Post = mongoose.model('Post', PostRule);
const User = mongoose.model('user', UserRule);
Post.find().populate('author').then(result => console.log(result));
在数据库中,author中的值为user中的id
命令行中运行如下: