Nodejs operation mongodb third (about the use of schema)

1. schemaDefault parameters

Many times we will set default parameters, and default this value when not inserting data

  • 1. Packaged connection database module

    // 第一步
    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. Define the usermodel

    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. Use a defined model

    const UserModel = require('./model/user');
    
    var user = new UserModel({
          
          
        name: '李四',
        age: 20
    });
    user.save((err) => {
          
          
        if (err) {
          
          
            console.log('保存数据错误')
        }
        console.log('保存数据成功');
    });
    
  • 4. Query data returned

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

Two, the mongoosepredefined pattern decorator

  • 1. The mongoosebuilt-in predefined modifiers mainly include

    • lowercase
    • uppercase
    • trim
  • 2. schemaUsed in

    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');
    

Three, mogoosethe predefined setand getmodifiers

We can also use set(recommended) modifiers to format the data when adding data. You can also use get(not recommended) to format the data when the instance gets the data, not when querying the data.

  • 1. Definitionschema

    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. Insert a piece of data

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

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

Four, mongodbthe index in

  • 1. The role of index

    An index is a structure that sorts the values ​​of one or more columns in a database table, which allows us to query the database
    faster. MongoDBThe index is almost exactly the same as the traditional relational database, which also includes some basic
    query optimization techniques.

  • 2. Create an index

    db.user.ensureIndex({
          
          字段:1}) // 普通索引
    
  • 3. Get the index

    db.user.getIndexes()
    
  • 4. Delete the index

    db.user.dropIndex({
          
          字段:1})
    
  • 5. Composite index

    // 数字 1 表示 username 键的索引按升序存储,-1 表示 age 键的索引按照降序方式存储
    db.user.ensureIndex({
          
          "username":1, "age":-1})
    
  • 6. Unique index

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

Five mongooseof schemacreating an index

  • 1. Define schemaa unique index when defining

    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');
    

Six, the use of time

  • 1. schemaUse timestampsattributes in the definition

    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. Create data

    const UserModel = require('./model/user');
    
    const user = new UserModel({
          
          
      name: '王五',
      age: 20,
      mobile: 100,
      status: 0
    });
    
    user.save();
    
  • 3. Query the data after creation

    {
          
          
        "_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. Modify createdAtand updatedAtdisplay

    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. The created data

    {
          
          
        "_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. Modify the data

    UserModel.updateOne({
          
           _id: '5e12ac19a1b9cfab59fbd913' }, {
          
           name: '王小二' }, (err, docs) => {
          
          
      if (err) {
          
          
        console.log('修改数据错误', err);
        return;
      }
      console.log(docs)
    })
    
  • 7. Modified data

    {
          
          
        "_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
    }
    

Seven, the use of plug-ins

  • 1. Plug-in search address

  • 2. Custom plug-ins

    // 定义一个插件
    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);
    

Guess you like

Origin blog.csdn.net/kuangshp128/article/details/103855734