MongoDB基础增删改查

1.连接数据库

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground') //playground数据库名称
	// 连接成功
	.then(() => console.log('数据库连接成功'))
	// 连接失败
	.catch(err => console.log(err, '数据库连接失败'));

2.如何创建集合以及向集合中插入文档

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接 
//{ useNewUrlParser: true, useUnifiedTopology: true }写上没有提示,不影响数据库操作,应该是版本老旧的原因
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
	// 连接成功
	.then(() => console.log('数据库连接成功'))
	// 连接失败
	.catch(err => console.log(err, '数据库连接失败'));

// 创建集合规则(sql的索引属性)
const courseSchema = new mongoose.Schema({
	name: String,
	author: String,
	isPublished: Boolean
});

// 使用规则创建集合
// 1.集合名称(就像sql表名一样)
// 2.集合规则
const Course = mongoose.model('Course', courseSchema) // courses

// 创建文档(创建数据内容)
const course = new Course({
	name: 'node.js基础',
	author: '黑马讲师',
	isPublished: true
});
// 将文档插入到数据库中
course.save();

3.向集合中插入文档的另一种方式

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
	// 连接成功
	.then(() => console.log('数据库连接成功'))
	// 连接失败
	.catch(err => console.log(err, '数据库连接失败'));

// 创建集合规则
const courseSchema = new mongoose.Schema({
	name: String,
	author: String,
	isPublished: Boolean
});

// 使用规则创建集合
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema) // courses

// 向集合中插入文档
// Course.create({name: 'Javascript', author: '黑马讲师', isPublished: false}, (err, result) => {
// 	console.log(err)
// 	console.log(result)
// })

Course.create({ name: 'Javascript123', author: '黑马讲师', isPublished: false })
	.then(result => {
		console.log(result)
	})

4.查询文档

// 创建集合规则
const userSchema = new mongoose.Schema({
	name: String,
	age: Number,
	email: String,
	password: String,
	hobbies: [String]
});

// 使用规则创建集合
const User = mongoose.model('User', userSchema);

// 1.查询用户集合中的所有文档
// User.find().then(result => console.log(result));

// 通过_id字段查找文档
// User.find({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result))

// 2.findOne方法返回一条文档 默认返回当前集合中的第一条文档
// User.findOne({name: '李四'}).then(result => console.log(result))

// 3.查询用户集合中年龄字段大于20并且小于40的文档
// User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result))

// 4.查询用户集合中hobbies字段值包含足球的文档
// User.find({hobbies: {$in: ['足球']}}).then(result => console.log(result))

// 5.选择要查询的字段
// User.find().select('name email -_id').then(result => console.log(result))

// 6.根据年龄字段进行升序排列
// User.find().sort('age').then(result => console.log(result))

// 7.根据年龄字段进行降序排列
// User.find().sort('-age').then(result => console.log(result))

// 8.查询文档跳过前两条结果 限制显示3条结果
User.find().skip(2).limit(3).then(result => console.log(result))

5.删除文档

// 查找到一条文档并且删除
// 返回删除的文档
// 如何查询条件匹配了多个文档 那么将会删除第一个匹配的文档
//User数据库
// User.findOneAndDelete({_id: '5c09f267aeb04b22f8460968'}).then(result => console.log(result)) 

// 删除多条文档
User.deleteMany({}).then(result => console.log(result))

6.更新文档

// 找到要删除的文档并且删除
// 返回是否删除成功的对象
// 如果匹配了多条文档, 只会删除匹配成功的第一条文档
//User数据库
// User.updateOne({name: '李四'}, {age: 120, name: '李狗蛋'}).then(result => console.log(result))

// 找到要删除的文档并且删除
User.updateMany({}, { age: 300 }).then(result => console.log(result))

7.mongoose验证

// 引入mongoose第三方模块 用来操作数据库
const mongoose = require('mongoose');
// 数据库连接
mongoose.connect('mongodb://localhost/playground', { 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 > 3
			},
			// 自定义错误信息
			message: '传入的值不符合验证规则'
		}
	}
});

const Post = mongoose.model('Post', postSchema);

Post.create({ title: 'aa', age: 60, category: 'javascript', author: 'bdfd' })
	.then(result => console.log(result))
	.catch(error => {
		// 获取错误信息对象
		const err = error.errors;
		// 循环错误信息对象
		for (var attr in err) {
			// 将错误信息打印到控制台中
			console.log(err[attr]['message']);
		}
	})

8.集合关联(sql的联表查询)

// 引入mongoose第三方模块 用来操作数据库
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: 'itheima' }).then(result => console.log(result));
// 创建文章
// Post.create({ title: '123', author: '5fa7ebffd0c3e33bcc4e52f7' }).then(result => console.log(result));

Post.find().populate('author').then(result => console.log(result))
原文地址:https://www.cnblogs.com/kawayi/p/13963046.html