1 year ago
#71497
anurag1905
Beginner in Mongoose: How to find if an array contains a value if I already have the document
I am trying to develop a banking website where users can apply for a loan. A single user can apply for multiple types of loans. Before a user successfully applies for a loan , I check if the user exists or not then I check all the loans for which the user has applied. If the user has already applied for the same type of loan then he/she will not be allowed to apply again.
For example, if a user has already applied for a home loan, he/she won't be allowed to apply for a home loan again.
Here is my User schema:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
email:{
type:String,
required:true,
unique:true
},
password:{
type:String,
required:true,
},
isAdmin:{
type:Boolean,
required:true
},
account:{
type:mongoose.Schema.Types.ObjectId,
ref:'Account',
required:false
},
transactions:{
type:mongoose.Schema.Types.ObjectId,
ref:'Transaction'
},
loans:[
{
type:mongoose.Schema.Types.ObjectId,
ref:'Loan'
}
]
},{
timestamps:true
});
const User = mongoose.model('User',userSchema);
module.exports = User;
Here is Loan Schema
const mongoose = require('mongoose');
const loanSchema = new mongoose.Schema({
user:{
type:mongoose.Schema.Types.ObjectId,
ref:'User',
required:true
},
amount:{
type:Number,
required:true,
},
account:{
type:mongoose.Schema.Types.ObjectId,
ref:'Account',
required:true
},
loantype:{
type:String,
required:true
}
},{
timestamps:true
});
const Loan = mongoose.model('Loan',loanSchema);
module.exports = Loan;
Here is what I have tried to do:
module.exports.apply = async function(req,res){
try{
let user = await User.findById(req.body.user)
.populate('account')
.populate({
path:'loans',
populate:{
path:'loantype'
}
});
let loan = await user.loans.find({loantype:req.body.loantype});
if(loan){
req.flash('error','Not Allowed');
return res.redirect('back');
}
req.flash('success','Applied Successfully');
return res.redirect('back');
}catch(err){
console.log('Error',err);
return res.redirect('back');
}
}
But this is not working. Any help will be much appreciated. Thanks !
mongodb
express
mongoose
mongoose-schema
mongoose-populate
0 Answers
Your Answer