MongoDB基础操作

MongoDB增删改查操作

MongoDB数据库服务启动和关闭

net start mongodb
net stop mongodb

数据库连接

先使用npm install mongoose安装mongoose依赖,之后使用mongoose提供的connect方法即可连接数据库。

const mongoose = require("mongoose");

mongoose
  .connect("mongodb://localhost/test")
  .then(() => console.log("数据库连接成功"))
  .catch(err => {
    console.log("数据库连接失败");
  });

ps:创建的数据库名字如果不存在,MongoDB会自动创建

创建集合

分为两步,

  1. 对集合设定规则
  2. 创建集合,创建mongoose.Schema构造函数的实例即可创建集合
//设定集合规则
const personSchema = new mongoose.Schema({
  name: String,
  age: Number,
});
创建集合并应用规则
const Person = mongoose.model("Person", personSchema); //数据库实际名称为persons

ps:刚创建好的集合在MongoDB Compass里面无法看到,是因为里面没有插入数据

创建文档

创建文档实际上就是向集合中插入数据

分为两步,

  1. 创建集合实例
  2. 调用实例对象下的save方法将数据保存到数据库中

方法一:

//创建文档
const person = new Person({
  name: "张三",
  age: 20,
});
//将文档插入到数据库中
person.save();

方法二:

Person.create({ name: "李四", age: 19 }, (err, doc) => {
  //错误对象
  console.log(err);
  //当前插入的文档
  console.log(doc);
});
Person.create({ name: "王五", age: 18 })
  .then((doc) => console.log(doc))
  .catch((err) => console.log(err));

mongoDB数据库导入数据

mongoimport -d 数据库名称 -c 集合名称 -file 要导入的数据文件

:mongoimport在使用之前需要先找到MongoDB安装目录bin目录下的mongoimport.exe所在的文件目录位置,将其添加到环境变量中即可使用

查询文档

//根据条件查找文档(条件为空则查找所有文档)
Person.find({ name: "张三" }).then((result) => console.log(result));
//返回文档集合
[{ 
	_id: 5f7a72120398013a3c338112, 
	name: '张三', 
	age: 20, 
	__v: 0 
}]
//根据条件查找文档
Person.findOne({ name: "李四" }).then((result) => console.log(result));
//返回文档集合
{ 
	_id: 5f7a75a84187ba391091e3dc, 
	name: '李四', 
	age: 19, 
	__v: 0 
}

两者的区别是,不管结果如何,find返回的都是一组文档,而findOne返回的都是一个文档

特殊的查询

//匹配大于 小于
Person.find({age: {$gt: 18, $lt: 20}}).then(result=>console.log(result))
//匹配包含,可以查询到文档数组里包含的信息
Person.find({hobbies: {$in: ['打篮球']}}).then(result=>console.log(result))
//选择要查询的字段
Person.find().select('name age -_id').then(result=>console.log(result))
//不想查询的字段在前面加个'-'则不显示
//将数据按照年龄进行升序排序
Person.find().sort('age').then(result=>console.log(result))
//将数据按照年龄进行降序排序
Person.find().sort('-age').then(result=>console.log(result))
//skip跳过多少条数据,limit限制查询数量
Person.find().skip(2).limit(2).then(result=>console.log(result))

删除文档

//查询到一条文档并且删除
//返回删除的文档
//如果查询条件匹配了多个文档,那么将会删除第一个文档
Person.findOneAndDelete({}).then(result=>console.log(result))
//删除多个
//返回删除的文档数目以及ok字段
Person.deleteMany({}).then(result=>console.log(result))

更新文档

//更新集合中的文档(更新一个)
Person.updateOne({查询条件},{要修改的值}).then(result=>console.log(result))
//例
Person.updateOne({name: '张三'},{name: '张三丰'}).then(result=>console.log(result))
//更新集合中的文档(更新多个)
//若查询条件为空,则更新所有值
Person.updateMany({查询条件},{要修改的值}).then(result=>console.log(result))
//例
Person.updateMany({},{age: 18}).then(result=>console.log(result))

mongoose验证

在创建集合规则时,可以设置当前字段的验证规则,验证失败就输入插入失败

const personSchema = new mongoose.Schema({
	title: {
		type: String,
		//必选字段
		required: [true, '请输入文章标题'],
		//字符串最小长度
		minlength: [2, '文章长度不能小于2'],
		//字符串最大长度
		maxlength: [5, '文章长度不能大于5'],
		//去除字符串两边空格
		trim: true
	},
	age: {
		type: Number,
		//数字的最小范围
		min: 18,
		max: 100
	},
	date: {
		type: Date,
		//默认值
		default: Date.now
	},
	category: {
		type: String,
		//枚举,列举出当前字段可以拥有的值
		enum: {
			values: ['html', 'css', 'javascript'],
			message: '分类的名称要在一定的范围内才可以'
		}
	},
	author: {
		type: String,
		//自定义验证器
		validate: {
			validator: v => {
				//返回布尔值
				//true验证成功,false验证失败
				//v是要验证的值
				return v && v.length> 4
			},
			//自定义错误信息
			message: '传入的值不符合验证规则'
		}
	}
})

打印不符合验证规则的信息

Person.create()
	  .then(result => console.log(result))
	  .catch(error => {
	  	//获取错误信息对象
	  	const err = error.errors;
	  	//循环错误信息对象
	  	for(var i in err){
	  		//将错误信息打印到控制台中
	  		console.log(err[i]['message'])
	  	}
	  })

集合关联

//用户集合规则
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: '张三'}).then(result => console.log(result))
//创建文章
Post.create({title: 'test', author: '5f7a72120398013a3c338112'}).then(result => console.log(result))
Post.find().populate('author').then(result => console.log(result))
posted @ 2020-10-05 10:08  actorhuang  阅读(125)  评论(0编辑  收藏  举报