简体   繁体   中英

Can access Mongoose model fields externally but not from within model method

I have the following mongoose schema:

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

In the same file, I define an instance method to tally a rental total for the member, using a prices object defined elsewhere:

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

In my routes file, I look up the member from inside a get function and pass member data into the member's page

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

After the findByID call, member has all its field defined correctly, and the balance call succeeds. However, it returns '0', as the instance fields are all undefined within that method.

If instead of

const balance = member.balance();

I use

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

it returns the correct total. homeController.balance is very similar:

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

How do I access the member's fields from within member.balance()?

Use a regular function rather than an arrow function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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