MongoDBデータベースのNode.js操作方法

** node.jsを使用してMongoDBデータベースを操作するには
、npm
installmongooseコマンドを使用しダウンロードするサードパーティパッケージmongooseに依存する必要があります。コマンドラインツールでnetstart mongoDBを実行してMongoDBを起動します。そうしないと、MongoDBは起動できません。接続します。
データベースを閉じて、net stop MongoDB
**を使用します

データベース接続:
mongooseが提供するconnetメソッドを使用してデータベースに接続します。
サンプルコード:

const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/playground',{
    
    useNewUrlParser: true,useUnifiedTopology: true})
	.then(() => console.log('数据库连接成功'))
	.catch(err => console.log(err,'数据库连接失败'));
	//箭头函数中若只有一个形式参数则可以省略括号,若代码只有一行则可以省略花括号
	//当前的playground为数据库的名称,若没有则先创建该数据库再进行连接
	//{useNewUrlParser: true,useUnifiedTopology: true}这两个参数为可选项,如果不加则会出现一些警告,但是不报错
//在MongoDB中不需要显示创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建

创建集合:
创建集合分为两步,一是对集合设定规则,二是创建集合,创建mongoose.Schema构造函数的实例即可创建集合
//设定集合规则
const courseSchema = new mongoose.Schema({
    
    
	name:String,
	author:String,
	isPublished:Boolean

});
//创建集合并应用规则
const Course = mongoose.model('Course',courseSchema);//courses
//第一个参数是文件名,第二个参数是引用mongoose.Schema创建的实例对象

创建文档:创建文档实际上就是向集合中插入数据
分为两步:1.创建集合实例 2.调用实例对象下的save方法将数据保存到数据库中
//创建集合实例
const course = new Course({
    
    
	name:'Node.js course',
	author:'cyy',
	isPublished:true
});
//将数据保存到数据库当中
course.save();

例:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{
    
    useUnifiedTopology: true,useNewUrlParser: true})
	.then(()=>console.log('666'))
	.catch(err=>console.log('555'));

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

const course = new Course({
    
    
	name:'Node.js course',
	author:'cyy',
	tags:['node','backend'],
	isPublished:true
});
//将数据保存到数据库当中
course.save();

创建文档:
Course.create({
    
    name:'JavaScript基础',author:'cyy',isPublish:true},(err,doc)=>{
    
    
	//错误对象
	console.log(err);
	console.log(doc);
});

创建文档:
Course.create({
    
    name:'JavaScript',author:'cyy',isPublish:true})
	.then(doc=>console.log(doc))
	.catch(err=>console.log(err))

有关数据库的操作都是异步操作

mongoDB数据库导入数据(查询数据)
mongoimport -d 数据库名称 -c 集合名称 --file 要导入的数据文件


查询文档:
//根据条件查找文档(条件为空则查找所有文档,以数组的形式呈现)
Course.find().then(result => console.log(result))

例:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{
    
    useUnifiedTopology: true,useNewUrlParser: true})
	.then(()=>console.log('666'))
	.catch(err=>console.log('555'));

//创建集合规则
const userSchema = new mongoose.Schema({
    
    
	name:String,
	author:String,
	isPublished:Boolean
});
const User = mongoose.model('courses',userSchema);
//查询用户集合中的所有文档
User.find().then(result => console.log(result));

查询文档2:
User.find({
    
    id:'xxxx'}).then(result => console.log(result));
//查询根据属性查询具体的数据
例:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{
    
    useUnifiedTopology: true,useNewUrlParser: true})
	.then(()=>console.log('666'))
	.catch(err=>console.log('555'));

//创建集合规则
const userSchema = new mongoose.Schema({
    
    
	name:String,
	author:String,
	isPublished:Boolean
});
const User = mongoose.model('courses',userSchema);
//查询用户集合中的所有文档
User.find({
    
    author:'cyy'}).then(result => console.log(result));

查询文档:
User.findOne({
    
    name:'李四'}).then(result => console.log(result))
//findOne方法返回一条文档 默认返回当前集合中的第一条文档,返回的是一个对象
//findOne方法中可以根据条件查找文档(条件为空则查找所有文档)

根据条件查询文档:
//匹配大于、小于  	$gt 大于 $lt小于
User.find({
    
    age:{
    
    $gt:20,$lt:50}}).then(result => console.log(result))

//匹配包含
User.find({
    
    hobbies:{
    
    $in:['敲代码']}}).then(result => console.log(result))

//选择要查询的字段 多个字段要以空格隔开 在select当中加入-_id可以不查询id
User.find().select('name email').then(result => console.log(result))

//将数据按照年龄进行排序,-age即为降序排列
User.find().sort('age').then(resule => console.log(result));

//skip 跳过多少条数据(文档) limit限制查询数量
User.find().skip(2).limit(2).then(resule => console.log(result));

删除文档:
//删除单个
Course.findOneAndDelete({
    
    name:'cyy'}).then(result => console.log(result))

//删除多个 输出结果n代表删除几个文档,ok值为1代表删除成功
Course.deleteMany({
    
    }).then(result => console.log(result))

更新文档:
//更新单个
User.updateOne({
    
    name:'cyy'},{
    
    name:'cyy1'}).then(resule => console.log(result))

//更新多个
User.updateMany({
    
    查询条件},{
    
    要改的值}).then(resule => console.log(resule))

例:User.updateMany({
    
    },{
    
    age:56}).then(resule => console.log(resule))
//传入一个空对象代表更改全部文档的年龄为56

mongoose验证
在创建集合规则时,可以设置当前字段的验证规则,验证失败则输入插入失败
required:true 必传字段(参数) 或者 required:[true,'自定义报错信息']
minlength:2 或者 minlength:[2,'文章最小长度是2']
maxlength:5 或者 maxlength:[5,'文章最大长度不能超过5']
trim:true //去除字符串两边的空格
min:2 数值最小为2
max:100 数值最大为100
enum['html','css','js','node.js']//枚举字段,传入的值必须包含在数组之中
自定义验证规则:validate:{
    
    
	validator:v =>{
    
    
		//返回布尔值
		//true 验证成功
		//false验证失败
		//v要验证的值
		v && v.lengrh > 4
	},
	//自定义错误信息
	message:'传入的值不符合验证规则'
}

获取错误信息
const Post = mongoose.model('Post',postSchema);
Post.create({
    
    title:'aa',age:60,category:'java',author:'bd'})
	.then(resule => console.log(resule))
	.catch(err => {
    
    
		const err = error.errors;
		
		for(var attr in err){
    
    
			console.log(err[attr]['message']);
		}
	})

集合关联:
通常不同集合的数据之间是有关系的,例如文章信息和用户信息储存在不同集合中,但文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联
1.使用id对集合进行关联
2.使用populate方法进行关联集合查询
文章集合:_id  tile  author  content
用户集合:_id  name  age  hobbies 
//用户集合
const User = mongoose.model('User',new mongoose.Schema({
    
    name:{
    
    type:String}}));
//文章集合
const Post = mongoose.model('Post',new mongoose.Schema({
    
    
	title:{
    
    type:String},
	//使用ID将文章集合和作者集合进行关联
	author:{
    
    type:mongoose.Schema.Types.ObjectId,ref:'User'}
}));
//联合查询
Post.find()
	.populate('author')
	.then((err,resule) => console.log(resule));

例:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{
    
    useUnifiedTopology: true,useNewUrlParser: true})
	.then(()=>console.log('666'))
	.catch(err=>console.log('555'));
//用户集合规则
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(resule => console.log(resule));
//创建文章
Post.create({
    
    title:'123',author:'复制用户集合的id'}).then(result => console.log(result));
Post.find().populate('author').then(result => console.log(result));

在创建集合规则时,unique:true可以保证字段的唯一性

![在这里插入图片描述](https://img-blog.csdnimg.cn/20210316002840557.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ppeXVlMTM=,size_16,color_FFFFFF,t_70)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210316004008893.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ppeXVlMTM=,size_16,color_FFFFFF,t_70)

--auth代表需要登录才能对数据库进行操作 --logpath和--dbpath是安装MongoDB时log目录和data目录下的文件和文件夹,只需要复制该文件的绝对路径即可,连接数据库时user代表用户名,pass代表密码,port代表端口号,默认是27017,database代表数据库的名字
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210316003223620.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ppeXVlMTM=,size_16,color_FFFFFF,t_70)
root代表超级管理员,readWrite代表可以读和写数据库,roles是一个数组,代表可以拥有多种身份

おすすめ

転載: blog.csdn.net/ziyue13/article/details/113819566