Mongoose cannot set property of “ ” to undefined,Whenever i try to create a new entry.Eventhough the schema is declared right

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

This line means your trying to set author on the Support variable, which is actually the schema definition, not your data. I think you want to change this line (and the one below it) to something like:

newsupport.author.id = req.user._id;
newsupport.auth.username = req.user.username;
newsupport.save();

Also, it looks like your creating then updating the document, why not just create the document with all the properties so you don’t have to update it after its created, as this requires more calls to the database.

1 Like

Thanks man worket out @bradtaniguchi