05-Node.js 操作 MongoDB 数据库

Node 操作 MongoDB 数据库

MongoDB 相关概念

术语 解释说明
database 数据库:
collection 集合:一组数据的集合(理解为一张表)
document 文档:一条具体的数据(理解为一行)
field 字段:文档中的属性名

Node 操作 MongoDB 的第三方包 - mongoose

  • 使用 mongoose 操作 MongoDB 数据库
  • 安装:npm install mongoose

启动和停止数据库

  • 启动:在命令行输入 net start mongodb
  • 停止:在命令行输入 net stop mongodb

MongoDB 导入数据

使用 mongoimport 导入数据,使用之前要确保 mongoimport.exe 所在的路径添加到环境变量

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

连接数据库

在 mongodb 不需要显式的创建数据库,但数据库不存在,mongodb 会自动创建

const mongoose = require('mongoose');
// 连接数据库
// 在mongodb不需要显式的创建数据库,但数据库不存在,mongodb会自动创建
mongoose.connect('mongodb://localhost/playground', {
        useUnifiedTopology: true,
        useNewUrlParser: true
    }).then(() => console.log('数据库连接成功'))
    .catch((err) => console.log(err, '数据库连接错误'))

创建集合以及文档

要想创建集合需要先创建集合规则,然后使用集合规则来创建集合

// 创建集合以及文档
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/playground', {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => {
        console.log('连接数据库成功');
    }).catch((err) => {
        console.log(err, '连接数据库错误');
    })

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

// 使用规则创建集合
// 1. 集合名称
// 2. 集合规则
// 返回一个构造函数, 这个构造函数就代表这个集合
const Course = mongoose.model('Course', courseSchema);

// 创建文档
// 创建一个集合构造函数的实列,
const course = new Course({
    name: 'node.js基础',
    author: '黑马',
    isPublished: true
})
// 调用实列对象的sava方法保存
course.save();

向集合中插入文档的另外一种方式

可以使用集合对象的 create 方法来插入文档

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/playground', {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => {
        console.log('连接数据库成功');
    }).catch((err) => {
        console.log(err, '连接数据库错误');
    })

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

const Course = mongoose.model('Course', courseSchema);

Course.create({
        name: 'Java',
    }).then(result => console.log(result))
    .catch(err => console.log(err))

查询文档

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

// 创建集合规则
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: '5c09f267aeb04b22f8460968'
}).then(result => console.log(result))

// findOne 方法返回一条文档,默认返回当前集合第一条文档
User.findOne({
    age: 10
}).then(result => console.log(result))

//  查找 age大于 20 小于 40的所有文档
User.find({
    age: {
        $gt: 20,
        $lt: 40
    }
}).then(result => console.log(result))

// 查找 hobbies 中包含 '足球' 文档
User.find({hobbies:{$in:['足球']}}).then(result=>console.log(result))

// 选择要查询的字段, 如果不想查询某个字段可以在字段的前面加上 -
User.find().select('name email -_id').then(result => console.log(result))

// 根据 age 字段进行升序排列
User.find().sort('age').then(result => console.log(result))
// 根据 age 字段进行降序排列
User.find().sort('-age').then(result => console.log(result))

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

删除文档

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

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

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

// 删除单个
User.findOneAndDelete({
    name: '张三'
}).then(result => console.log(result))

// 删除多个文档, 如果没有查询条件,就会删除全部
User.deleteMany({}).then(result=>console.log(result))

更新文档

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

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

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

// 更新集合中的单个文档 updateOne({查询条件}, {要求修改的值})
User.updateOne({name:'张三'}, {name:'张三updata'}).then(result=>console.log(result))

// 更新集合中的多个文档
User.updateMany({}, {
    age: 56
}).then(result => console.log(result))

mongoose 验证

/**
 * required: true 必传字段
 * minlength 最小长度
 * maxlength 最大长度
 * trim 去除首尾空格
 * min 数字的最小范围
 * max 数字的最大范围
 * default 默认值
 * enum 枚举,列出当前字段可以拥有的值
 */

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

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        // 属性值传入一个列表, 列表的第二项为错误提示
        required: [true, '请传入文章标题'],
        minlength: 2,
        maxlength: 6,
        trim: true,
    },
    age: {
        type: Number,
        min: 18,
        max: 100,
    },
    publishDate: {
        type: Date,
        default: Date.now,
    },
    category: {
        type: String,
        // enum 类型的设置方法
        enum: {
            values : ['html', 'css', 'js'],
            message : '分类名称要在范围内'
        }
    },
    author: {
        type: String,
        // 自定义验证器
        validate: {
            validator: (v) => {
                // 返回布尔值, 成功返回 true, 否则返回 false
                return v.trim.lenght > 4
            },
            // 自定义错误信息
            message: "不符合"
        }
    }
})

const Post = mongoose.model('Post', postSchema)

Post.create({
        title: '     111            ',
        age: 60,
        category: 'java',
        author: '   123      '
    }).then(result => console.log(result))
    .catch(error => {
        // 获取错误信息对象
        let errList = error.errors;
        // 循环错误信息对象
        for (let attr in errList) {
            // 将错误信息打印到控制台中
            console.log(errList[attr]['message']);
        }
    })

集合关联

const mongoose = require('mongoose');
// 连接数据库
mongoose.connect('mongodb://localhost/playground', {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .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'
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }
})

// 创建用户集合
const User = mongoose.model('User', userSchema);

// 创建文章集合
const Post = mongoose.model('Post', postSchema);

// 创建用户
// User.create({
//     name: 'xiaowen1'
// }).then(result => console.log(result))

// 创建文章
// Post.create({
//     title : 'post1',
//     author:'5db4054eefe45d807c8b435e'
// }).then(result=>console.log(result))

// 关联查询 => populate
Post.find().populate('author').then(result => console.log(result))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,372评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,368评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,415评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,157评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,171评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,125评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,028评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,887评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,310评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,533评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,690评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,411评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,004评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,812评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,693评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,577评论 2 353