目 录CONTENT

文章目录

mongoose使用

Administrator
2021-04-22 / 0 评论 / 0 点赞 / 5365 阅读 / 8695 字 / 正在检测是否收录...

mongoose使用

mongoose安装

$ npm install mongoose --save

$ yarn add mongoose

启动MongoDB

以服务形式安装的可以直接启动服务

$ net start mongodb

连接数据库

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

创建集合

创建集合分为两步,一是对集合设定规则,二是创建集合

//设定集合规则
const courseSchema = new mongoose.Schema({
    name:String,
    author:String,
    isPublished:Boolean
});
//创建集合并应用规则
const Course = mongoose.model("Course",courseSchema);
//这个时候创建的集合名称为courses

创建文档

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

第一种方式

分为两步:

  1. 创建集合实例
  2. 调用实例对象下的save方法将数据保存到数据库中
//创建集合的实例
const course = new Course({
    name:"softeem course",
    author:"标哥哥",
    tags:["node","mongodb"],
    isPublished:true
});
//将数据保存到数据库中
course.save();

第二种方式

Course.create({
    name:"JavaScript基础",
    author:"标哥哥",
    isPublished:true
},(err,doc)=>{
    //错误对象
    console.log(err);
    //当前插入的文档
    console.log(doc);
})

上面的create方法也可以使用Promise的方式来进行

Course.create({
    name:"JavaScript基础",
    author:"标哥哥",
    isPublished:true
}).then(result=>{
    console.log(result);
}).catch(err=>{
    console.log(err);
})

导入数据

这里我们使用mongoDB数据库导入数据

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

如果提示mongoimport命令不能识别,请注意添加mongodb的环境变量

查询文档

在集合的构造函数下面,有一个find()方法,它是用于查询对象,它返回一个Promise对象

find查询

//根据条件查找文档(条件为空则查找所有文档)
Course.find().then(result=>{
    console.log(result);
});

上面的result就是查询返回的结果 ,它是一个数组

[
    {
        _id:"5e8459375909e2004d490668",
        name:"JavaScript基础",
        author:"标哥哥"
    },{
    	_id:"5e835425fd7cde004d7b8559",
        name:"bootstrap",
        author:"二当家的"
    }
]

上面是一个最基础的查询方式,我们现在在看下面的例子

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

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

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

上面的代码是查询所有文档,我们也可以添加查询条件来进行查询

//通过_id来查找文档
User.find({
    _id:"5e835425fd7cde004d7b8559"
}).then(result=>{
    console.log(result);
})

通过find方法来查询的结果是一个数组,即使查询不到数据返回的也是一个空数组

findOne查询

User.findOne().then(result=>console.log(result));

findOne方法默认返回集中的第一个文档。当然findOne方法也可以进行条件查询

User.findOne({
    name:"标哥哥"
}).then(result=>{
    console.log(result);
});

匹配大于、小于

//年龄大于20,小于40的
User.find({
    age:{
        $gt:20,
        $lt:50
    }
}).then(result=>{
    console.log(result);
});

匹配包含

在刚刚定义User的结构里面,我们看到有一个爱好这个属性,它是一个数组,如果我们想匹配数组时面的某一项,应该怎么办呢?

User.find({
    hobbies:{
        $in:["逛街"]
    }
}).then(result=>{
    console.log(result);
})

选择要查询的字段

默认情况下,mongoose在查询的时候返回的文档的所有字段,我们可以通过select来指定要返回的字段

User.find().select("name email -_id")
	.then(result=>{
        console.log(result);
    });

在上面的代码里面,我们可以看到有一个select的方法,同时我们看到_id的前面有一个-,这代表排除这个字段

排序

升序排列

//根据age来进行升充排序
User.find().sort("age")
	.then(result=>{
    	console.log(result);
	});

降序排列

User.find().sort("-age")
	.then(result=>{
    	console.log(result);
	});

skip与limit分页

User.find().skip(2).limit(2)
	.then(result=>{
        console.log(result);
    })
  • skip代表跳过多少条记录
  • limit代表取多少条记录

删除文档

mongodb在删除文档之前要先查找到这个文档

删除单个findOneAndDelete

Course.findOneAndDelete({
     _id:"5e8459375909e2004d490668"
}).then(result=>{
    console.log(result);
})

result代表的是你删除的文档

删除多个deleteMany

User.deleteMany({
    //这里是查询条件
}).then(result=>{
   console.log(result); 
});

result返回的是对象,格式{n:5,ok:1},n代表删除的数量,ok代表删除的状态是否成功

更新文档

更新单个updateOne

User.updateOne({查询条件},{要改的值})
	.then(result=>{
    	console.log(result);
	});

我们现在根据上面的语法格式来具体实现一下

User.updateOne({
    name:"二当家的"
},{
    name:"大当家的"
}).then(result=>{
    console.log(result);
});

udpateOne即使找到了多个文档,更新的也只是第一个文档

更新多个updateMany

多个的更新与单个的更新语法格式差不多

User.updateMany({
    //这里是空对象,代表更新所有
},{
    age:18
}).then(result=>{
   console.log(result); 
});

mongoose验证

在创建集合的时候,我们可以设置当前字字段的验证规则

  • require:true 必值字段
  • minlength:3 字符串最小长度
  • maxlength:20字符串最大长度
  • trim:true去除字符串左右的空格
  • min:2 最小值
  • max:32 最大值
  • default默认值
  • enum使用枚举限定值
  • validate自定义验证规则
const postSchema = new mongoose.Schema({
    title:{
        type:String,
        require:[true,"请输入案例标题"],
        minlength:[2,"标题长度不能小于2"],
        maxlength:[5,"标题长度不能超过5"],
        trim:true
    },
    age:{
        type:Number,
        max:100,
        min:18
    },
    publishDate:{
        type:Date,
        default:Date.now
    },
    category:{
        type:String,
        enum:["新闻","小说","技术"]
    },
    author:{
        type:String,
        validate:{
            validator:(v)=>{
                //返回boolean值
                //true代表验证成功,false代表验证失败
               return v&&v.length>4
            },
            //自定义错误信息
            message:"传入的值不符合验证规则"
        }
    }
});
const Post = mongoose.model("Post",postSchema);

集合关联

通常不同集合的数据之间是有关系的,例如文章的信息和用户的信息储存在不同的集合中,但文档是某个用户发表的,要查询文档的所有信息包括发表用户,就需要用到集合关系

image-20200418203738322

上图就是两个表的基本结构,文档集合的author这个字段存储的就是用户集合中的_id字段

//用户集合
const User = mongoose.model("User",new mongoose.Schema({
    name:{
        type:String
    }
}));

//文章集合
const Post = mongoose.model("Post",new mongoose.Schema({
    title:{
        type:String
    },
    author:{
        type:mongoose.Schema.Types.ObjectId,
        ref:"User"
    }
}));

//联合查询
Post.find()
	.populate("author")
	.then((err,result)=>{
    	console.log(result);
	});
0

评论区