You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mongoose中为Model添加可直接调用的自定义方法?

在Mongoose中为模型添加自定义方法的实现方式

要实现可直接通过Mongoose模型调用的自定义方法,你需要使用schema.statics对象来定义,而非用于文档实例的schema.methods。模型级方法内部的this指向模型本身,可直接调用模型的内置操作(如查询、创建、统计等)。

代码示例

首先定义Schema并添加模型级自定义方法:

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
  name: String,
  logins: [{ status: String, createdAt: Date }]
});

// 定义模型级自定义方法
userSchema.statics.myCustomMethodToCall = async function(targetStatus) {
  // this 指向 UserModel 本身
  // 示例操作:统计包含指定登录状态的用户数量
  const matchedUserCount = await this.countDocuments({
    'logins.status': targetStatus
  });
  
  // 你也可以在这里实现其他模型级逻辑,比如批量更新、创建批量用户等
  return matchedUserCount;
};

const UserModel = mongoose.model('User', userSchema);

使用方式

直接通过模型调用该方法即可:

// 调用模型自定义方法,统计成功登录的用户数
const successUserCount = await UserModel.myCustomMethodToCall('success');
console.log(`拥有成功登录记录的用户总数:${successUserCount}`);

内容的提问来源于stack exchange,提问作者Islam Y-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 09:31:14