代码之家  ›  专栏  ›  技术社区  ›  Peter Christodoulou

可以从外部访问Mongoose模型字段,但不能从模型方法内部访问

  •  0
  • Peter Christodoulou  · 技术社区  · 9 年前

    const memberSchema = new mongoose.Schema({
        name: String,
        roomA: Boolean,
        roomB: Boolean,
        roomC: Boolean,
    });
    

    在同一个文件中,我使用在别处定义的prices对象定义了一个实例方法来统计成员的租金总额:

    memberSchema.methods.balance = () => {
        let total = 0;
    
        if (this.roomA) {total += prices.roomA;}
        if (this.roomB) {total += prices.roomB;}
        if (this.roomC) {total += prices.roomC;}
    
        return total;
    }
    
    mongoose.model('Members', memberSchema);
    

    在我的routes文件中,我从get函数中查找成员,并将成员数据传递到成员的页面中

    return members.findById(req.id).then(member => {
        console.log(member);
        const balance = member.balance();
        res.render('members/home', {
            title: 'Welcome ' + member.name,
            "balance" : balance,
        });
    });
    

    在findByID调用之后,成员的所有字段都已正确定义,余额调用成功。但是,它返回“0”,因为该方法中的实例字段都未定义。

    如果而不是

    const balance = member.balance();
    

    我使用

    const balance = homeController.balance({member, prices});
    

    它返回正确的总数。homeController。平衡非常相似:

    exports.balance = (req, res) => {
        let total = 0;
    
        if (req.member.roomA) {total += req.prices.roomA;}
        if (req.member.roomB) {total += req.prices.roomB;}
        if (req.member.roomC) {total += req.prices.roomC;} 
    
        return total;
    }
    

    如何从成员内访问成员的字段。balance()?

    1 回复  |  直到 9 年前
        1
  •  0
  •   Steve Holgado    9 年前

    使用常规函数而不是箭头函数:

    memberSchema.methods.balance = function() {
      let total = 0;
    
      if (this.roomA) {total += prices.roomA;}
      if (this.roomB) {total += prices.roomB;}
      if (this.roomC) {total += prices.roomC;}
    
      return total;
    }