使用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 __
相关产品推荐
相关产品推荐

