【问题标题】:Instance Methods inside Mongoose Schema not workingMongoose Schema 中的实例方法不起作用
【发布时间】: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");
  }
});

为什么第一个选项不起作用?谢谢。

【问题讨论】:

    标签: mongoose instance-methods


    【解决方案1】:

    “静态”和“方法”应该是一个论点的一部分。

    不是

    const userSchema = new mongoose.Schema({}, 
    { statics: {}},
    { methods: {}},
    )
    

    const userSchema = new mongoose.Schema({}, 
        { 
            statics: {},
            methods: {},
        },
      )
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2022-01-22
      • 2016-09-04
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 2021-04-18
      • 2020-03-26
      • 1970-01-01
      相关资源
      最近更新 更多