mongodb的mongoose框架增删改查及链表(二)

在Node中mongoose增删改查及链表

欢迎点击: 个人官网博客

1.创建并连接mongodb数据库

先npm 下载sequelize以及mysql2

//playground为数据库名称
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', {
    
     useUnifiedTopology: true, useNewUrlParser: true })//连接数据库
    .then(() => {
    
    
        console.log('数据库链接成功')
    })
    .catch(err => {
    
    
        console.log('数据库链接失败', err)
    })

2.创建表(集合)

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', {
    
     useUnifiedTopology: true, useNewUrlParser: true })//连接数据库
    .then(() => {
    
    
        console.log('数据库链接成功')
    })
    .catch(err => {
    
    
        console.log('数据库链接失败', err)
    })
//创建集合(表)规则,字段
const courseSchema= new mongoose.Schema({
    
    
    name: String,
    author: String,
    isPubilc: Boolean
})
//创建集合(表),参数:表名称,规则
const Course= mongoose.model('Course',courseSchema)//如果有第三个参数,默认操作第三个参数的表
//创建集合(表)实例
const course =new Course({
    
    
    name: 'node.js讲解',
    author: '小明',
    isPubilc: true
})
//将数据保存到数据库
course.save()

3.在表(集合)中增删改查

//-----------------------------增
Course.create({
    
    name:'javascript123',author:'龚',isPubilc:false})
.then((res) => {
    
    
    console.log(res)
})
.catch(err => {
    
    
    console.log(err)
})
//-----------------------------删
User.findOneAndDelete({
    
    _id:'5f6085b8c664a03760dbec4f'}).then(res=>console.log(res))
//删除多条数据
User.deleteMany({
    
    }).then(res=>console.log(res))

//-----------------------------改

//更新单个,匹配到的第一个,第一个参数为查询条件
Course.updateOne({
    
    author:'龚'},{
    
    author:'小龚'}).then(res=>console.log(res))
// 更新多个
//第一个括号为要更改的人查询条件,不写就是所有,第二个就是要改成的参数
Course.updateMany({
    
    },{
    
    name:'es6'}).then(res=>console.log(res))


// ----------------------------查
 Course.find()//查询所有
    .then((res) => {
    
    
         console.log(res)
     })
    .catch(err => {
    
    
        console.log(err)
     })
 Course.find({
    
    _id:'5f6079637397d4327840d3d9'})//按需查询,返回数组
     .then((res) => {
    
    
         console.log(res)
     })
     .catch(err => {
    
    
         console.log(err)
     })
// ---------------------findone返回查询到的第一个
 Course.findOne({
    
    author:'龚'})//按需查询
     .then((res) => {
    
    
        console.log(res)
    })
   .catch(err => {
    
    
        console.log(err)
    })
// --------------查数量
 Course.count({
    
    name:'es6'},(err,res)=>console.log(res,err))

 Course.findOneAndRemove({
    
    name:'es5'},(err,res)=>console.log(res,err))//删除

User.find({
    
    age:{
    
    $gt:21,$lt:50}})//匹配大于小于
    .then((res) => {
    
    
        console.log(res)
    })
    .catch(err => {
    
    
        console.log(err)
    })

User.find({
    
     name: {
    
     $in: ['react'] } })//匹配包含
    .then((res) => {
    
    
        console.log(res)
    })
    .catch(err => {
    
    
        console.log(err)
    })

User.find().select('name -_id')//查询出一些个字段,前面加一个-表示不查这个字段,默认带id所以去掉他
    .then((res) => {
    
    
        console.log(res)
    })
    .catch(err => {
    
    
        console.log(err)
    })

User.find().sort('age')//根据字段升序排序
    .then((res) => {
    
    
        console.log(res)
    })
    .catch(err => {
    
    
        console.log(err)
    })

User.find().sort('-age')//加一个 - 根据字段降序排序
    .then((res) => {
    
    
        console.log(res)
    })
    .catch(err => {
    
    
        console.log(err)
    })

4.链表及复杂操作

// 创建 model
mongoose.connect('mongodb://localhost/playground', {
    
     useUnifiedTopology: true, useNewUrlParser: true })//连接数据库
    .then(() => {
    
    
        console.log('数据库链接成功')
    })
    .catch(err => {
    
    
        console.log('数据库链接失败', err)
    })
const aSchema = new mongoose.Schema({
    
    
    name: String
})
const bSchema = new mongoose.Schema({
    
    
    author: {
    
    
        type: mongoose.Schema.Types.ObjectId,
        ref: 'A'
    },
    title: String
})
const A = mongoose.model('A', aSchema)
const B = mongoose.model('B', bSchema)

关键来了

//链表查询
 B.aggregate([
        {
    
    
            $lookup: {
    
    //可多个lookup
                from: 'courses',//子表的名字
                localField: 'title',//父表的关联项,当前表
                foreignField: 'name',//子表的关联项
                as: 'items'//查询到的子集放到哪个字段数组里
            }
        },
        {
    
    
            $match: {
    
     'title': 'es6' }//父表的筛选类似于find
        }, 
        {
    
    
            $project: {
    
     title: 1, _id: 1 }//父表查询出来后要显示的字段
        },
        {
    
    
            $sort: {
    
     title: 1 }//父表查询排序
        },
        {
    
    
           $limit:10
        },
        {
    
    
           $skip:10
        }
    ], (err, data) => {
    
    
        console.log(data)
        res.send(JSON.stringify(data))
    })

5.最后说一下创建表(集合)的规则

const postSchema = new mongoose.Schema({
    
    
    name: {
    
    
        type:String,
        required:true,//表示必须传
        minlength:[2,'长度不能小于2个字符'],//最小长度,还可以自定义报错信息
        maxlength:5,
        trim:true,//去掉前后空格
        match:/^'龚'(.*)/,//正则表达式
        // unique:true//限制是唯一的索引
        // index:true//普通索引
    },
    age: {
    
    
        type:Number,
        required:[true,'请传入年龄'],//自定义报错信息
        max:[30,'年龄不能大于30岁'],
    },
    date:{
    
    
        type:Date,
        default:Date.now//默认值为当前时间
    },
    category:{
    
    
        type:String,
        enum:{
    
    
            values:['html','css','js','es6'],//枚举,只能传 其中的一项
            message:'分类名称错误'
        }
    }
})

猜你喜欢

转载自blog.csdn.net/qq_41560520/article/details/111353808