繁体   English   中英

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

[英]Can access Mongoose model fields externally but not from within model method

我有以下猫鼬模式:

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

在同一文件中,我定义了一个实例方法,使用在其他地方定义的price对象来计算成员的租金总额:

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);

在我的路由文件中,我从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.balance非常相似:

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;
}

如何从member.balance()中访问成员的字段?

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

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM