You need to enable JavaScript to run this app. Mongoose开启timestamps时报错$__isSelected is not a function如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose开启timestamps时报错$__isSelected is not a function如何解决

问题根因

该错误绝大多数情况下由以下两类问题触发:

  1. 项目中存在多个版本的Mongoose实例混用,导致模型实例的原型方法缺失
  2. 未正确注册Mongoose模型,直接使用Schema实例创建数据对象

修复方案

方案1:修复多版本Mongoose依赖问题

从你提供的堆栈信息可以明显看出依赖冲突:Mongoose核心逻辑加载自根目录node_modules/mongoose,而中间件依赖kareem加载自src/submodules/node_modules/kareem,说明你的子模块中也单独安装了Mongoose,两个版本的Mongoose实例方法不兼容导致缺少$__isSelected私有方法。
修复步骤:

  • 删除根目录、子模块目录下的node_modules文件夹,以及对应的锁文件(package-lock.json/yarn.lock/pnpm-lock.yaml)
  • 统一项目的Mongoose版本:仅在根项目的package.json中声明Mongoose依赖,子模块如果需要Mongoose,将其声明为peerDependency而非直接依赖
  • 重新执行依赖安装命令

方案2:检查模型注册逻辑

确认你是通过mongoose.model方法生成的Notification模型类,而非直接导出Schema使用,正确的注册逻辑如下:

const mongoose = require('mongoose')
const notificationSchema = require('./你的schema文件路径')
// 必须经过mongoose.model包装才能生成可用的模型类
const Notification = mongoose.model('Notification', notificationSchema)

方案3:兼容替代方案

如果暂时无法解决依赖冲突,可以手动实现时间戳功能,无需依赖timestamps配置:

"use strict";

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const notificationSchema = new Schema(
  {
    type: String,
    author: String,
    metadata: Object,
    link: String,
    // 手动添加时间戳字段
    createdAt: { type: Date, default: Date.now },
    updatedAt: { type: Date, default: Date.now }
  }
);

// 新增save中间件自动更新updatedAt
notificationSchema.pre('save', function(next) {
  this.updatedAt = Date.now();
  next();
});

module.exports = mongoose.model('Notification', notificationSchema);

内容的提问来源于stack exchange,提问作者Phantom007

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 01:15:04