NodeJs学习笔记(六)使用Mongoose

1.创建集合和文档

const mongoose = require('mongoose');

//步骤1:连接数据库
mongoose.connect('mongodb://localhost/playground') //这句代码返回一个Promise对象
    .then(() => console.log("Conneted to Mongodb......"))
    .catch(err => console.log("Cound not connect to Mongodb...",err));

//步骤2:创建schema,我们使用schema创建数据集合的结构
const courseSchema = mongoose.Schema({
    name: String,
    auther: String,
    tags: [ String ],
    date: { type: Date, default: Date.now },
    isPublished: Boolean
});
const Course = mongoose.model('Course',courseSchema); //返回值是一个类,故用大写命名

//创建课程的异步方法
async function createCourse(){
    const course = new Course({
        name:'计算机网络',
        auther:'zijeak',
        tags: ['internet','web','router'],
        isPublished:false
    });
    
    const result = await course.save(); //save()是一个异步方法,它返回一个Promise对象
    console.log(result);
}
//调用方法
createCourse()

以上操作会在playground数据库内的course集合中插入一个文档

{
  tags: [ 'internet', 'web', 'router' ],
  _id: 5ead27609e14e33fd8ab6b18,
  name: '计算机网络',
  auther: 'zijeak',
  isPublished: false,
  date: 2020-05-02T07:55:12.877Z,
  __v: 0
}

2.查询文档

2.1 一般查询

async function getCourses(){
    const result = await Course.find() //返回一个DocumentQuery对象,这个对象有些像Promise对象,也有then方法
    console.log(result);
}
getCourses();
[
  {
    tags: [ 'internet', 'web', 'router' ],
    _id: 5ead27609e14e33fd8ab6b18,
    name: '计算机网络',
    auther: 'zijeak',
    isPublished: false,
    date: 2020-05-02T07:55:12.877Z,
    __v: 0
  },
  {
    tags: [ '算法', '递归', '复杂度' ],
    _id: 5ead288e74fe1004acd74e13,
    name: '数据结构',
    auther: '刘晓霞',
    isPublished: true,
    date: 2020-05-02T08:00:14.066Z,
    __v: 0
  }
]

2.2 过滤

也可以在find方法内加入用于过滤的参数

const result = await Course.find({auther:'zijeak'})

加入其它筛选条件:

const result = await Course
    .find({auther:'zijeak'}) //返回一个DocumentQuery对象,这个对象有些像Promise对象,也有then方法
    .limit(10)
    .sort({name:1})//按照name,正序排序
    .select({name:1,tags:1})//决定返回哪些属性
[
  {
    tags: [ 'internet', 'web', 'router' ],
    _id: 5ead27609e14e33fd8ab6b18,
    name: '计算机网络'
  }
]

2.3 比较查询

加入比较操作符:

eq(equal)
ne(not equal)
gt(greater than)
gte(greater than or equal to)
lt(less than)
lte(less than or equal to)
in (in)
nin(not in)
在使用比较操作符时,我们使用对象来代替一个具体的值,例如用{ $gt : 10 }来代替10

.find({ price : { $gt : 10 } })

2.4 逻辑查询

在查询时使用逻辑操作符
or、and

async function getCourses(){
    const result = await Course
    .find() //返回一个DocumentQuery对象,这个对象有些像Promise对象,也有then方法
    .or({ auther:'zijeak' },{ isPublished:true })
    console.log(result);
}
getCourses();

2.5 使用正则表达式查询

const result = await Course
    .find({auther:/^z/}) 

2.6 计数

const result = await Course
    .find() //返回一个DocumentQuery对象,这个对象有些像Promise对象,也有then方法
    .count();

2.7 分页

async function getCourses(){
    const pageNumber = 2;
    const pageSize = 1;
    //  api/courses?pageNumber=2&pageSize=4

    const result = await Course
    .find() //返回一个DocumentQuery对象,这个对象有些像Promise对象,也有then方法
    .skip( (pageNumber - 1) * pageSize )//跳过这页之前的所有页
    .limit(pageSize);
    console.log(result);
}

3.更新文档

方法1:

//更新课程:方法一
async function updateCourse_1(id){
    const course = await Course.findById(id);
    if(!course) return;
    // course.isPublished = true;
    // course.auther = 'lele';
    course.set({
        isPublished:true,
        auther:'lele'
    });
    const result = await course.save();
    console.log(result);
}

方法2:

async function updateCourse_2(id){
    const result = await Course.update({_id:id},{
        $set:{
            auther:"new",
            isPublished:false
        }
    });
    
    console.log(result);
}
pdateCourse_2('5ead947805af8018fc18d8fe');

在这里插入图片描述

async function updateCourse_2(id){
    const result = await Course.findByIdAndUpdate({_id:id},{
        $set:{
            auther:"old",
            isPublished:false
        }
    });
    
    console.log(result);
}

上面这段代码返回未修改过的

在这里插入图片描述
可以用在findByIdAndUpdate方法中传入第三个参数实现返回更新后的文档:

async function updateCourse_2(id){
    const result = await Course.findByIdAndUpdate({_id:id},{
        $set:{
            auther:"old",
            isPublished:false
        }
    },{new:true});
    
    console.log(result);
}

4.删除文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值