This is my MongooseModel
const mongoose = require('mongoose');
const { boolean } = require('webidl-conversions');
const memberSchema = mongoose.Schema({
name:{
type:String,
required:[true,"Please enter Customer Name"]
},
age:{
type:Number,
required:[true,"Please enter your age"]
},
address:{
type:String,
required:[true,"Please enter your Address"]
},
phone:{
type:String,
required:[true,"Please enter your phone number"],
minLength:[10,"Phone number must be 10 digits"],
maxLength:[10,"Phone number must be 10 digits"],
},
avatar:{
public_id:String,
url:String
},
joining:{
type:Date,
default:Date.now
},
status:{
type:Boolean,
default:true,
},
membership:{
user:{
type:mongoose.Schema.ObjectId,
ref:"Member",
},
membershipAmount:{
type:Number,
},
membershipStart:{
type:Date,
},
membershipPeriod:{
type:Number,
},
membershipEnd:{
type:Date,
},
signUpFee:{
type:Number,
default:500
}
},
});
module.exports=mongoose.model("Member",memberSchema);
memberSchema.methods.planValidity=function(){
this.membershipEnd=new Date(this.membershipStart+(this.membershipPeriod*24*60*60*1000));
}
Now I want to use this method planValidity inside a controller while creating a new user.
exports.addMember = catchAsyncErrors(async(req,res,next)=>{
const member = await Member.create(req.body);
res.status(201).json({
success:true,
member
});
});
How do I call the method so that my MembershipStart and membershipEnd gets updated.
3
Answers
Something like this might work.
If
membershipStart
andmembershipPeriod
properties are initialized while creating Member then, mongooseprehook(save)
can be used to update themembershipEnd
property.mongoose middleware documentation link: https://mongoosejs.com/docs/middleware.html#pre
Note:
All mongoose document instance methods must define before the model created.
I don’t really understand what’s the problem you’re having.
You need to fix your
planValidity
method. BothmembershipEnd
andmembershipPeriod
are undermembership
property.memberSchema.methods.planValidity=function(){
this.membershipEnd=new Date(this.membershipStart+(this.membershipPeriod2460601000));}
After fixing the method, you can just call it as a normal function: