I am creating a presence list for my Gym Management project and at the home page the user has to enter his email in order to validate his presence, presence is validated if user's Membership, but I can't figure out how to do it.
Here's the Membership Model `
const mongoose = require('mongoose');
const membershipSchema = new mongoose.Schema({
credit:{
type:String,
required:true
},
isActive:{
type:Boolean,
default:true,
},
expiresAt:{
type:Date,
min:'2022-12-07'
},
user:
{
type:mongoose.Schema.Types.ObjectId,
ref:'User',
required:false,
}
})
module.exports = mongoose.model("Membership",membershipSchema);
`
Here's the user model :
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name:{
type:String,
trim:true,
required:true
},
email:{
type:String,
trime:true,
required:true,
unique:true
},
address:
{
type:String,
required:true,
},
phone:
{
type:String,
required:true,
}
})
module.exports = mongoose.model("User",userSchema);
Here's the code i use to find the Membership by User
`
exports.findMembership = async (req,res) =>{
const query = {};
if(req.body.email)
{
query.email = req.body.email
}
const user = await User.find(query).select("_id")
if(userId)
{
query.user = userId;
Membership.find(query,(err,membership)=>{
if(err)
{
res.status(400).json({error:JSON.stringify(err)})
}
res.json(membership)
}).populate('user');
}
//return res.status(404);
}
`
I tried fetching the user first by it's email and it works but when i try the second request in the same function it gives back nothing HomePage POSTMAN PLZ help I need to get this done by the end of the week
CodePudding user response:
You are setting the user variable but checking the if condition against userId variable. You should change your findMembership function to below:
exports.findMembership = async (req,res) =>{
const query = {};
if(req.body.email)
{
query.email = req.body.email
}
const userId = await User.find(query).select("_id")
if(userId)
{
query.user = userId;
Membership.find(query,(err,membership)=>{
if(err)
{
res.status(400).json({error:JSON.stringify(err)})
}
res.json(membership)
}).populate('user');
}
//return res.status(404);
}