MongoDB增删改查(下)

143 阅读3分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第27天,点击查看活动详情

2.5 删除文档

删除单个

User.findByIdAndDelete({_id: '5c09f2b6aeb04b22f846096a'}).then(result => console.log(result))

删除多个

User.deleteMany({}).then(result => console.log(result))

2.6 更新文档

更新单个

User.updateOne({name: '李四'}, {name: '李逍遥'}).then(result => console.log(result))

更新多个

User.updateMany({}, {age: 56}).then(result => console.log(result))

2.7 mongoose 验证

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

  • required: true 必传字段
  • minlength:3 字符串最小长度
  • maxlength: 20 字符串最大长度
  • trim: true 去除字符串两边的空格
  • min: 2 数值最小为2
  • max: 100 数值最大为100
  • enum: ['html' , 'css' , 'javascript' , 'node.js']
  • validate: 自定义验证器
  • default: 默认值

示例:

const mongoose = require('mongoose');
​
mongoose.connect('mongodb://localhost/playground')
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.log('数据库连接失败', err))
​
​
const postSchema = new mongoose.Schema({
    title: {
        type: String,
        // 必选字段
        required: true,
        // 字符串的最小长度
        minlength: 2,
        // 字符串的最大长度
        maxlength: 5,
        // 去除字符串两边的空格
        trim: true
    },
    age: {
        type: Number,
        // 数值最小
        min: 18,
        // 数值最大
        max: 100
    },
    publishDate: {
        type: Date,
        // 默认值
        default: Date.now
    },
    category: {
        type: String,
        // 枚举限定内容
        enum: ['html', 'css', 'javascript', 'node.js']
    },
    author: {
        type: String,
        validate: {
            validator: v => {
                // 返回布尔值
                // true 验证成功
                // false 验证失败
                // v 要验证的值
                return v && v.length > 4
            },
            // 自定义错误信息
            message: '传入的值不符合验证规则'
        }
    }
});
​
const Post = mongoose.model('Post', postSchema);
Post.create({title: 'abc', age: 60, category: 'javascript',author: 'aaaaa'}).then(res => console.log(res))

2.8 集合关联

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

  • 使用id对集合进行关联
  • 使用populate方法进行关联集合查询

image.png 集合关联实现

const mongoose = require('mongoose');
​
mongoose.connect('mongodb://localhost/playground')
    .then(() => console.log('数据库连接成功'))
    .catch(err => console.log('数据库连接失败', err))
​
​
// 用户集合规则
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: 'xiaogao'}).then(res => console.log(res))// 创建文章
// Post.create({title: '123', author: '6212589048801e6764839db4'}).then(res => console.log(res))// 联合查询
Post.find().populate('author').then(res => console.log(res))

2.9 案例:用户信息增删改查

这个案例前端用的都是拼接字符串,没啥好在博客中展示的,在gitee中有完整代码。

  1. 搭建网站服务器,实现客户端与服务器端的通信

    const express = require('express')
    const app = express()
    ​
    app.listen(8080, () => {
        console.log('Express server running at http://127.0.0.1');
    })
    
  2. 连接数据库,创建用户集合,向集合中插入文档

    const mongoose = require('mongoose')
    ​
    mongoose.connect('mongodb://localhost/playground')
        .then(() => console.log('数据库连接成功'))
        .catch(err => console.log('数据库连接失败', err))
    ​
    const userSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true,
            minlength: 2,
            maxlength: 20
        },
        age: {
            type: Number,
            min: 18,
            max: 80
        },
        password: String,
        email: String,
        hobbies: [ String ]
    })
    ​
    // 创建集合,返回集合构造函数
    mongoose.model('User', userSchema)
    
  3. 当用户访问/list时,将所有用户信息查询出来

  4. 将用户信息和表格HTML进行拼接并将拼接结果响应回客户端

  5. 当用户访问/add时,呈现表单页面,并实现添加用户信息功能

  6. 当用户访问/modify时,呈现修改页面,并实现修改用户信息功能

  7. 当用户访问/delete时,实现用户删除功能