MongoDB删除文档,更改文档,验证,集合关联

删除文档在这里插入图片描述

不加判断条件,默认删除所有文档。
在这里插入图片描述

更新文档

更新集合中的文档
在这里插入图片描述

User.updateOne({name: '王五'}, {name: '李aa'}).then(result => console.log(result))

在这里插入图片描述

mongoose验证

在创建集合规则时,可以设置当前字段的验证规则,验证失败就输入插入失败。
在这里插入图片描述

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));
发布了67 篇原创文章 · 获赞 5 · 访问量 1974

猜你喜欢

转载自blog.csdn.net/Zmongo/article/details/105135445