im building a support portal webiste.Where i have to record which user is raising the ticket.
Im using passport so i can get the username and _id through req.user.Im using express and MongoDB Atlas as my database.I have saved my database schemas on a seaparate folder called models.
Here is the schema file:
const mongoose=require("mongoose");
const supportSchema=new mongoose.Schema({
type:String,
comment:String,
date:String,
status:String,
author:{
id:{
type:mongoose.Schema.Types.ObjectId,
ref:"User"
},
username:String
}
})
module.exports=mongoose.model("Support",supportSchema);
and here is the express side of things :
//posting support to admin
app.post("/admin/support",isLoggedIn,function(req,res){
const data={
type:req.body.type,
comment:req.body.comment,
status:"Pending"
}
Support.create(data,function(err,newsupport){
console.log(req.user);
if(err){
console.log(err);
}else{
//add username and id to ticket
Support.author.id=req.user._id;
Support.author.username=req.user.username;
// save ticket
Support.save();
res.redirect("/home");
}
})
})
As we can see in the schema above, i have defined author and inside author i have defined id.Im running into a error whenever im trying to create a ticket.It tells me “Cannot set property ‘id’ of undefined”.
I even crosschecked by console logging req.user(which im able to access inside the route).
I have required the schema in app.js
const Support=require("./models/newsupport");
PS:name of the file is newsupport.
i have configured mongodb connection like so:
mongoose
.connect('mongodb+srv://saidarshan:R@mb02501@cluster0-wjhf4.mongodb.net/project?retryWrites=true&w=majority', {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(() => {
console.log('Connected to DB');
})
.catch((err) => {
console.log('ERROR', err.message);
});
Please help me out with this.Thank you