User.updateOne({name: '王五'}, {name: '李aa'}).then(result => console.log(result))
在创建集合规则时,可以设置当前字段的验证规则,验证失败就输入插入失败。
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('连接成功'))
.catch(() => console.log('连接失败'));
const postSchema = new mongoose.Schema({
title: {
type: String,
required: [true,'请传入文章标题'],
minlength: [2, '文章长度不能小于2'],
maxlength: [5, '文章长度最大不能超过5'],
//去除两边的空格
trim: true
},
age: {
type: Number,
//数字的最小值范围
min: [18, '最小年龄为18'],
//数字的最大值范围
max: [100,'最大年龄为100']
},
publishDate: {
type: Date,
//默认值
default: Date.now
},
category: {
type: String,
//枚举 列举出当前字段可以拥有的值
enum: {
values: ['html', 'css', 'javascript', 'node.js'],
message: '请输入正确分类名称'
}
},
author: {
type: String,
validate: {
validator: v => {
//返回布尔值
return v && v.length > 4
},
//自定义错误信息
message: '传入的值不符合验证规则'
}
}
});
const Post = mongoose.model('Post', postSchema);
Post.create({title: ' as', age: 20,category: 'htl',author: 'bh'})
.then(result => console.log(result))
.catch(error => {
//获取错误信息对象
const err = error.errors;
//循环错误信息对象
for (var attr in err) {
//将错误信息打印到控制台中
console.log(err[attr]['message']);
}
})
通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,但是文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。
规定字段中ObjectId的类型:type: mongoose.Schema.Types.ObjectId,
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{useNewUrlParser: true, useUnifiedTopology: true})
.then(() => console.log('数据库连接成功'))
.catch(err => console.log(err, '数据库连接失败'));
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
}
});
const postSchema = new mongoose.Schema({
title: {
type: String
},
author: {
type: mongoose.Schema.Types.ObjectId,
//要关联的集合
ref: 'User'
}
});
// 创建用户和文章集合
const User = mongoose.model('User', userSchema);
const Post = mongoose.model('Post', postSchema);
//创建用户
User.create({name: 'ithema'}).then(result => console.log(result));
//创建文章
Post.create({title: '345', author: '5e7da94a252b1d184cf73897'}).then(result => console.log(result));
Post.find().populate('author').then(result => console.log(result));