美文网首页
Node MongoDB数据库

Node MongoDB数据库

作者: 赫丹 | 来源:发表于2020-04-28 16:24 被阅读0次

1.下载地址

https://www.mongodb.com/download-center/community

2. Mongoose第三方包

  • 使用Node.js操作MongoDB数据库需要依赖Node.js第三方包mongoose
  • 使用npm install mongoose命令下载

3. 启动MongoDB

使用管理员打开在命令行工具中运行
net start mongodb 启动MongoDB Server,否则MongoDB将无法连接。
net stop mongodb 停止mongoDB Server

4. 连接数据库与创建

使用mongoose提供的connect方法即可连接数据库
在MongoDB中不需要显式创建数据库,如果正在使用的数据库不存在,MongoDB会自动创建。

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

5. MongoDB增删改查操作

5.1创建集合

创建集合分为两步,一是对对集合设定规则,二是创建集合,创建mongoose.Schema构造函数的实例即可创建集合

// 设定集合规则
 const courseSchema = new mongoose.Schema({
     name: String,
     author: String,
     isPublished: Boolean
 });
  // 创建集合并应用规则
 const Course = mongoose.model('Course', courseSchema); // courses
5.2创建文档

创建文档实际上就是向集合中插入数据。
分为两步:
1.创建集合实例。
2.调用实例对象下的save方法将数据保存到数据库中。
示例1

// 创建集合实例
 const course = new Course({
     name: 'Node.js course',
     author: 'ithedan',
     tags: ['node', 'backend'],
     isPublished: true
 });
  // 将数据保存到数据库中
 course.save();

示例2

Course.create({name: 'node', author: 'ithedan', isPublish: true}, (err, doc) => { 
     //  错误对象
    console.log(err)
     //  当前插入的文档
    console.log(doc)
});

示例3

////支持 promise写法
Course.create({name: 'node', author: 'ithedan', isPublish: true})
      .then(doc => console.log(doc))
      .catch(err => console.log(err))
5.3 mongoDB数据库导入数据
  • mongoimport –d 数据库名称 –c 集合名称 –file 要导入的数据文件
  • 找到mongodb数据库的安装目录,将安装目录下的bin目录放置在环境变量中。
5.4 查询文档
//查询用户集合中的所有文档
User.find().then(result => console.log(result));
//通过_id字段查找文档
User.find({_id:'5c09f1e5aeb04b22f8460965'}).then(result=>console.log(result));
//findOne方法返回一条文档,默认返回当前集合中的第一条文档
User.findOne().then(result => console.log(result));
User.findOne({name: '李四'}).then(result => console.log(result));
//查询用户集合中年龄字段大于20并且小于40的文档$gt 大于  $lt 小于
User.find({age: {$gt: 20, $lt: 40}}).then(result => console.log(result));
// 查询用户集合中hobbies字段值包含足球的文档 $in  包含匹配
User.find({hobbies: {$in:['足球']}}).then(result => console.log(result));
// 选择要查询的字段  不查询字段  前面加-
User.find().select('name email -_id').then(result => console.log(result));
// 根据年龄字段进行升序排列
User.find().sort('age').select('name age -_id').then(result => console.log(result));
// 根据年龄字段进行降序排列
User.find().sort('-age').select('name age -_id').then(result => console.log(result));
// 查询文档跳过前两条结果 限制显示3条结果skip  limt  分页用
User.find().skip(2).limit(3).then(result => console.log(result));
5.5 删除文档
// 查找到一条文档并且删除  返回删除的文档
// 如何查询条件匹配了多个文档 那么将会删除第一个匹配的文档
User.findOneAndDelete({_id:'5c09f1e5aeb04b22f8460965'}).then(result => console.log(result));
//删除多条数据
User.deleteMany({}).then(result => console.log(result));
5.6 更新文档
// 查找到一条文档并且修改  返回修改状态
// 如何查询条件匹配了多个文档 那么将会修改第一个匹配的文档
// User.updateOne({查询条件},{要修改的值}).then(result=>console.log(result));
User.updateOne({name:'张三'},{age:34,name:'邓晓'}).then(result=>console.log(result));
// User.updateMany({查询条件},{要修改的值}).then(result => console.log(result));
User.updateMany({}, {age: 1100}).then(result => console.log(result));
5.7mongoose验证

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

  • required: true 必传字段
  • minlength:3 字符串最小长度
  • maxlength: 20 字符串最大长度
  • min: 2 数值最小为2
  • max: 100 数值最大为100
  • enum: ['html', 'css', 'javascript', 'node.js']
  • trim: true 去除字符串两边的空格
  • validate: 自定义验证器
  • default: 默认值
    获取错误信息:error.errors['字段名称'].message
//创建规则
const postSchema = new mongoose.Schema({
        title: {
            type: String,
            // //必选字段
            required: [true, '请输入文章标题'],
            // //字符串的最小长度
            minlength: [2, '文章长度不能小于2'],
            // //字符串的最大长度
            maxlength: [5, '文章长度最大不能超过5'],
            //去除两边空格
            trim: true
        },
        age: {
            type: Number,
            //数字的最小范围
            min: [18, '最小年龄18'],
            //数字最大范围
            max: 100
        },
        publishDate: {
            type: Date,
            //默认值
            default: Date.now
        },
        //分类
        category: {
            type: String,
            // 枚举 列举出当前字段可以拥有的值
            enum: {
                values: ['html', 'css', 'javascript', 'node.js'],
                message: '分类名称要在一定的范围内才可以'
            }
        },
        author: {
            type: String,
            validate: {
                validator: v => {
                    // 返回布尔值
                    // true 验证成功
                    // false 验证失败
                    // v 要验证的值
                    return v && v.length > 4
                },
                // 自定义错误信息
                message: '传入的值不符合验证规则'
            }
        }
    })
5.8集合关联实现
// 用户集合
const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } })); 
// 文章集合
const Post = mongoose.model('Post', new mongoose.Schema({
    title: { type: String },
    // 使用ID将文章集合和作者集合进行关联
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}));
//联合查询
Post.find()
      .populate('author')
      .then((err, result) => console.log(result));

6 mongoDB数据库添加账号

  1. 以系统管理员的方式运行powershell
  2. 连接数据库 mongo
  3. 查看数据库 show dbs
  4. 切换到admin数据库 use admin
  5. 创建超级管理员账户 db.createUser({user:'root',pwd:'******',roles:['root']})
  6. 切换到blog数据 use blog
  7. 创建普通账号 db.createUser({user:'ithedan',pwd:'******',roles:['readWrite']})
    readWrite读写权限
  8. 卸载mongodb服务
    1. 停止服务 net stop mongodb
    2. mongod --remove
  9. 创建mongodb服务(logpath 日志目录 dbpath 存储目录 --install安装 --auth 当前数据库必须在登录的情况下进行操作)
    mongod --logpath="C:\Program Files\MongoDB\Server\4.1\log\mongod.log" --dbpath="C:\Program� Files\MongoDB\Server\4.1\data" --install –-auth
  10. 启动mongodb服务 net start mongodb
  11. 在项目中使用账号连接数据库
    mongoose.connect(mongodb: //user :pass @localhost : port /database')

相关文章

网友评论

      本文标题:Node MongoDB数据库

      本文链接:https://www.haomeiwen.com/subject/fkxbwhtx.html