【发布时间】:2023-02-01 18:41:19
【问题描述】:
我正在尝试将“方法”添加到架构中。我通过模式选项为“方法”对象分配了一个函数。但它不起作用(返回错误)。
const userSchema = new mongoose.Schema({},
{ statics: {}},
{ methods: {
generateAuthToken() {
const token = jwt.sign({ _id: this._id.toString() }, "nodejstraining");
return token;
},
}
)
当我将一个函数分配给“方法”对象时,代码正在运行(我得到了令牌):
userSchema.methods.generateAuthToken = function () {
const token = jwt.sign({ _id: this._id.toString() }, "nodejstraining");
return token;
};
这是一个路由器:
router.post("/users/login", async (req, res) => {
try {
const user = await .... // I'm getting a 'user' here
const token = await user.generateAuthToken();
res.send({ user, token });
} catch (err) {
res.status(400).send("Unable to login");
}
});
为什么第一个选项不起作用?谢谢。
【问题讨论】: