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

使用passport-local-mongoose时遇userSchema.plugin is not a function错误

问题解决:userSchema.plugin is not a function

你遇到的错误是因为定义的userSchema是普通JavaScript对象,而plugin是Mongoose Schema实例的专属方法,普通对象不具备这个方法。

修正方法

把普通对象形式的Schema定义,改成使用mongoose.Schema构造函数创建Schema实例:

const mongoose = require("mongoose");
const plm = require("passport-local-mongoose");

mongoose.connect(
  `mongodb+srv://Funn:000000@cluster0.q3gng0d.mongodb.net/`, 
  {
    dbName: "Auth"
  }
).then((c) => console.log("db connected", c.connection.host))
  .catch((e) => console.log(e));

// 改用mongoose.Schema创建Schema实例
const userSchema = new mongoose.Schema({
  username: String,
  password: String,
  secret: String,
});

userSchema.plugin(plm); 

module.exports = mongoose.model("user", userSchema); 

原因说明

Mongoose的Schema必须是mongoose.Schema的实例,才能调用plugin、pre、post等Schema专属扩展方法。普通对象只是基础数据结构,不具备这些Mongoose提供的功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 15:01:24