虚拟属性

new Schema({
  firstName: {
    type: String
  },
  lastName: {
    type: String
  },
  fullName: {
    virtual: true, // 虚拟属性,不会持久化到数据库
    get(){
      // 读取该属性时运行的函数
      return this.firstName + " " + this.lastName;
    }
  }
})

模型方法

var schema = new Schema({});
schema.methods.methodName = fn; // 添加实例方法
schema.static("methodName", fn); // 添加静态方法

案例

  1. User.js

    var mongoose = require("mongoose");
    const { updateIfCurrentPlugin } = require("../mongoose-update-if-current/lib");
    var Schema = mongoose.Schema;
    const addressSchema = require("./addressSchema");
    
    var userSchema = new Schema({
      loginId: {
        type: String,
        required: true,
        unique: true,
        trim: true,
        minlength: 3,
        maxlength: 18,
      }, // String is shorthand for {type: String}
      loginPwd: {
        type: String,
        required: true,
        trim: true,
        select: false,
      },
      name: {
        type: String,
        required: true,
        trim: true,
        minlength: 2,
        maxlength: 10,
      },
      age: {
        type: Number,
        default: 18,
      },
      loves: {
        type: [String],
        default: [],
      },
      address: {
        type: addressSchema,
        required: true,
      },
      // 虚拟属性
      info: {
        type: String,
        virtual: true,
        get() {
          return `姓名:${this.name}, 年龄: ${this.age}`;
        },
      },
      operations: [{ type: Schema.Types.ObjectId, ref: "Operation" }],
    });
    
    // 模型方法:实例方法
    userSchema.methods.print = function () {
      console.log(`
        姓名: ${this.name}
        年龄: ${this.age}
        爱好:${this.loves.join(",")}
      `);
    };
    
    // 模型方法:静态方法
    userSchema.static("getUsers", async function (page = 1, limit = 10, keywords = "") {
      const skip = (page - 1) * limit;
      const reg = new RegExp(keywords);
      const filter = { $or: [{ name: reg }, { loginId: reg }] };
      
      const total = await this.countDocuments(filter);
      const datas = await this.find(filter).skip(skip).limit(limit);
    
      return { total, datas };
    });
    
    userSchema.plugin(updateIfCurrentPlugin);
    module.exports = mongoose.model("User", userSchema);
    
  2. index.js

    var { User, Operation } = require("./models");
    
    async function test() {
      // 使用静态方法
      const us = await User.getUsers(1, 2, "邓");
      console.log(us);
    }
    
    test();
    
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 虚拟属性
  2. 2. 模型方法
  3. 3. 案例