[英]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.