• Node中使用MongoDB


    简介

    MongoDB 中文文档

    MongoDB是一个介于关系数据库和非关系数据库(nosql)之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

    Mongoose

    在Node中可以使用 Mongoose库来连接数据库

    mongoose中文文档

    npm i mongoose  -s
    

    基础操作

    连接数据库

    const mongoose = require('mongoose');
    
    //连接指定数据库
    mongoose.connect(
        'mongodb://ip地址/数据库名称',
        {
            useNewUrlParser: true,
            useUnifiedTopology: true
        }
    );
    const conn = mongoose.connection;
    //绑定连接完成监听
    conn.on('connected',function () {
        console.log('数据库连接成功');
    })
    

    创建model

    • 用Schema来定义数据对象的结构

    • 通过 mongoose.model(表名,数据对象) 来定义model

    //得到对应特定集合的model (文档:数据对象, 集合:数据表)
    const Schema = mongoose.Schema;
    const userSchema = new Schema({ //文档结构: 属性名属性值
        name: { type: String, default: 'hahaha' },
        age: { type: Number, min: 18, index: true },
        bio: { type: String, match: /[a-z]/ },
        password: {type:String,select: false} //select: false 表示当返回对象时,不包含该属性
    });
    
    //定义Model
    const UserModel = mongoose.model('user',userSchema);//创建了users集合
    

    增删查改

    通过上一步创建的Model来实现增删查改

    相关的CRUD函数: https://mongoosejs.com/docs/queries.html

    //增
    function saveTest() {
        //创建实例
        const userModel = new UserModel({
            username: 'admin',
            age: 19,
            bio:"z",
            password:md5('12345') //利用 blueimp-md5库,将密码加密
        });
    
        userModel.save(function (err, data) {
            console.log('save()',err,data);
        })
    }
    //删
    function deleteTest() {
        UserModel.deleteOne(
            {
                _id: '5e4d1c324abf031e98915a65'
            },(err, product) => {
             console.log('delete ',err,product);
            }
        )
    }
    //查 通过find()/findOne()/findById
    function findTest() {
        UserModel.find(
            (err,doc)=>{
                console.log('find()',err,doc)
            }
        );
    
        UserModel.findOne({username: 'admin'},
            function (err,doc) {
                console.log('findOne()',err,doc)
            })
    }
    
    //改
    function updateTest() {
        UserModel.findByIdAndUpdate({
            _id: '5e4d1c324abf031e98915a65'
        },{
            username: 'newName'
        },
            function (err,doc) {
                console.log('findByIdAndUpdate',err,doc)
            })
    }
    

    官方的条件查询例子

    // With a JSON doc
    Person.
      find({
        occupation: /host/,
        'name.last': 'Ghost',
        age: { $gt: 17, $lt: 66 },
        likes: { $in: ['vaporizing', 'talking'] }
      }).
      limit(10).
      sort({ occupation: -1 }).
      select({ name: 1, occupation: 1 }).
      exec(callback);
    
    // Using query builder
    Person.
      find({ occupation: /host/ }). //模糊查询:正则表达式
      where('name.last').equals('Ghost').
      where('age').gt(17).lt(66).
      where('likes').in(['vaporizing', 'talking']).
      limit(10).
      sort('-occupation').
      select('name occupation').
      exec(callback);
    

    条件操作符:
    $gt -------- greater than >

    $gte --------- gt equal >=

    $lt -------- less than <

    $lte --------- lt equal <=

    $ne ----------- not equal !=

    $eq -------- equal =

    $in:[] 满足其中一个在该数组之内 其相反为 $nin

    limit 读取指定数量的记录 skip 跳过指定数量的记录

    升降排序 升序关键字:'asc' / 'ascending' / 1 降序关键字:'desc' / 'descending' / -1
    // 以 "field" 升序 并且 "test" 降序
    query.sort({ field: 'asc', test: -1 });
    // 等同于
    query.sort('field -test');

    select 用于包含和排除某些属性
    // include a and b, exclude other fields
    query.select('a b');
    // exclude c and d, include other fields
    query.select('-c -d');

  • 相关阅读:
    第5次系统综合实践
    第4次系统综合实践
    第3次系统综合实践
    第2次实践作业
    第1次实践作业
    第03组 Beta版本演示
    第03组 Beta冲刺(4/4)
    OO第四单元总结
    OO第三单元总结
    OO第二单元总结
  • 原文地址:https://www.cnblogs.com/deus/p/12341589.html
Copyright © 2020-2023  润新知