Nodejs operation mongodb fourth (the use of methods)

1. mongooseBuilt-in CURDofficial website address

Two, schemaextend the static method yourself

  • 1. schemaExtend static methods in

    UserSchema.statics.findByName = function(name, callback) {
          
          
        this.findOne({
          
          name}, (err, docs) => {
          
          
            callback(err, docs);
        })
    }
    
  • 2. Use static methods

    UserModel.findByName('张三', (err, docs) => {
          
          
        console.log(docs);
    })
    

Three, schemaextend the instance method yourself

The so-called instance method is similar to the savefunction when creating data

  • 1. schemaExtend the example method in (the project is less used)

    // 扩展实例方法
    UserSchema.methods.print = function(){
          
          
        console.log(this, '实例方法');
    }
    
  • 2. Use custom instance methods

    var user = new UserModel({
          
          
        name: '   李四   ',
        age: 20,
        message1: 'hello',
        message2: 'word'
    });
    
    user.print();
    

Guess you like

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