Nodejs操作mongodb3番目(スキーマの使用について)

1.schemaデフォルトパラメータ

多くの場合、デフォルトのパラメータを設定し、データを挿入しない場合はこの値をデフォルトにします

  • 1.パッケージ接続データベースモジュール

    // 第一步
    const mongoose = require('mongoose');
    
    // 第二步连接数据库
    mongoose.connect('mongodb://root:123456@localhost/nest_cms', {
          
           useNewUrlParser: true }, (err) => {
          
          
        if (err) {
          
          
            console.log('连接错误');
            return;
        }
        console.log('mongodb连接成功');
    });
    
    module.exports = mongoose;
    
  • 2.userモデルを定義します

    const mongoose = require('./db');
    
    const UserSchema = mongoose.Schema({
          
          
        name: String,
        age: Number,
        status: {
          
           // 默认参数
            type: Number,
            default: 1,
        }
    })
    
    module.exports=mongoose.model('User',UserSchema,'user');
    
  • 3.定義されたモデルを使用する

    const UserModel = require('./model/user');
    
    var user = new UserModel({
          
          
        name: '李四',
        age: 20
    });
    user.save((err) => {
          
          
        if (err) {
          
          
            console.log('保存数据错误')
        }
        console.log('保存数据成功');
    });
    
  • 4.返されたクエリデータ

    [ {
          
           status: 1,
        _id: 5e0fdb9d6e124d1f3096d9f3,
        name: '张三',
        age: 20,
        __v: 0 },
      {
          
           status: 1, // 默认插入的是1
        _id: 5e0fdbca98ff701f9006afcd,
        name: '李四',
        age: 20,
        __v: 0 } ]
    

2、mongoose事前定義されたパターンデコレータ

  • 1.mongoose組み込みの定義済み修飾子には、主に次のものが含まれます。

    • lowercase
    • uppercase
    • trim
  • 2.でschema使用

    const mongoose = require('./db');
    
    const UserSchema = mongoose.Schema({
          
          
        name: {
          
          
            type: String,
            trim: true,
        },
        age: Number,
        message1: {
          
          
            type: String,
            lowercase: true,
        },
        message2: {
          
          
            type: String,
            uppercase: true,
        },
        status: {
          
          
            type: Number,
            default: 1,
        }
    })
    
    module.exports=mongoose.model('User',UserSchema,'user');
    

三、mogoose事前に定義されたsetget修飾子

set(推奨)修飾子を使用して、データを追加するときにデータをフォーマットすることもできます。getデータのクエリ時ではなく、インスタンスがデータを取得するときにデータをフォーマットするために使用することもできます(非推奨)。

  • 1.定義schema

    const mongoose = require('./db');
    
    const NewSchema = mongoose.Schema({
          
          
        title: {
          
          
            type: String,
            trim: true,
        },
        author: String,
        avatar: {
          
          
            type: String,
            set(url) {
          
          
                if (!url) {
          
          
                    return '';
                }
                if (url.indexOf('http://') !=0 && url.indexOf('https://') !=0) {
          
          
                    url = 'http://' + url;
                }
                return url;
            }
        }
    })
    
    module.exports = mongoose.model('New', NewSchema, 'new');
    
  • 2.データを挿入します

    const NewModel = require('./model/new');
    
    const news = new NewModel({
          
          
        title: '文章一',
        author: '张三',
        avatar: 'xx.png'
    })
    
    news.save();
    
  • 3.クエリ結果

    {
          
          
        "_id" : ObjectId("5e0fe0b971428227107241c1"),
        "title" : "文章一",
        "author" : "张三",
        "avatar" : "http://xx.png",
        "__v" : 0
    }
    

四、mongodbインデックス

  • 1.インデックスの役割

    インデックスは、データベーステーブルの1つ以上の列の値を並べ替える構造であり、データベースを
    より高速にクエリできますMongoDBインデックスは、いくつかの基本的な
    クエリ最適化手法も含まれている従来のリレーショナルデータベースとほぼ同じです。

  • 2.インデックスを作成します

    db.user.ensureIndex({
          
          字段:1}) // 普通索引
    
  • 3.インデックスを取得します

    db.user.getIndexes()
    
  • 4.インデックスを削除します

    db.user.dropIndex({
          
          字段:1})
    
  • 5.複合インデックス

    // 数字 1 表示 username 键的索引按升序存储,-1 表示 age 键的索引按照降序方式存储
    db.user.ensureIndex({
          
          "username":1, "age":-1})
    
  • 6.一意のインデックス

    db.user.ensureIndex({
          
          "userid":1},{
          
          "unique":true})
    

ファイブmongooseschemaインデックスを作成します

  • 1.定義schema時に一意のインデックスを定義します

    const mongoose = require('./db');
    
    const UserSchema = mongoose.Schema({
          
          
        name: {
          
          
            type: String,
            trim: true,
            unique: true, // 创建唯一索引
        },
        age: Number,
        message1: {
          
          
            type: String,
            lowercase: true,
        },
        message2: {
          
          
            type: String,
            uppercase: true,
        },
        status: {
          
          
            type: Number,
            default: 1,
        }
    })
    
    module.exports=mongoose.model('User',UserSchema,'user');
    

六、時間の使い方

  • 1.定義で属性をschema使用するtimestamps

    var mongoose = require('./db.js');
    
    var UserSchema = new mongoose.Schema({
          
          
      name: String,
      age: Number,
      mobile: Number,
      status: {
          
          
        type: Number,
        default: 1
      }
    }, {
          
          
      //设置时间戳
      timestamps: true
    });
    
    module.exports = mongoose.model('User', UserSchema, 'user');
    
  • 2.データを作成します

    const UserModel = require('./model/user');
    
    const user = new UserModel({
          
          
      name: '王五',
      age: 20,
      mobile: 100,
      status: 0
    });
    
    user.save();
    
  • 3.作成後にデータをクエリします

    {
          
          
        "_id" : ObjectId("5e12a7f6c63086a54eed0a47"),
        "status" : 0,
        "name" : "王五",
        "age" : 20,
        "mobile" : 100,
        "createdAt" : ISODate("2020-01-06T03:22:30.336Z"), // 与系统默认时间相差8小时
        "updatedAt" : ISODate("2020-01-06T03:22:30.336Z"),
        "__v" : 0
    }
    
  • 4.変更createdAtしてupdatedAt表示します

    var mongoose = require('./db.js');
    
    
    var UserSchema = new mongoose.Schema({
          
          
      name: String,
      age: Number,
      mobile: Number,
      status: {
          
          
        type: Number,
        default: 1
      }
    }, {
          
          
      //设置时间戳
      timestamps: {
          
          
        createdAt: 'created_at',
        updatedAt: "updated_at"
      }
    });
    
    module.exports = mongoose.model('User', UserSchema, 'user');
    
  • 5.作成されたデータ

    {
          
          
        "_id" : ObjectId("5e12ac19a1b9cfab59fbd913"),
        "status" : 0,
        "name" : "马六",
        "age" : 20,
        "mobile" : 100,
        "created_at" : ISODate("2020-01-06T03:40:09.560Z"),
        "updated_at" : ISODate("2020-01-06T03:40:09.560Z"),
        "__v" : 0
    }
    
  • 6.データを変更します

    UserModel.updateOne({
          
           _id: '5e12ac19a1b9cfab59fbd913' }, {
          
           name: '王小二' }, (err, docs) => {
          
          
      if (err) {
          
          
        console.log('修改数据错误', err);
        return;
      }
      console.log(docs)
    })
    
  • 7.変更されたデータ

    {
          
          
        "_id" : ObjectId("5e12ac19a1b9cfab59fbd913"),
        "status" : 0,
        "name" : "王小二",
        "age" : 20,
        "mobile" : 100,
        "created_at" : ISODate("2020-01-06T03:40:09.560Z"),
        "updated_at" : ISODate("2020-01-06T03:42:51.022Z"),
        "__v" : 0
    }
    

セブン、プラグインの使用

  • 1.プラグイン検索アドレス

  • 2.カスタムプラグイン

    // 定义一个插件
    const lastModified = (schema, option) => {
          
          
      schema.add({
          
           updated_at: Date });
      schema.pre('updateOne', (next) => {
          
          
        this.updated_at = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        next();
      })
    }
    
    // 使用插入
    UserSchema.plugin(lastModified);
    

おすすめ

転載: blog.csdn.net/kuangshp128/article/details/103855734