我有以下mongoose架构:
const memberSchema = new mongoose.Schema({
name: String,
roomA: Boolean,
roomB: Boolean,
roomC: Boolean,
});
在同一个文件中,我定义了一个实例方法来计算会员的租金总额,使用其他地方定义的价格对象:
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()中访问成员的字段?
答案 0 :(得分:0)
使用常规功能而不是箭头功能:
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;
}