Am working on Ticket system module using MERN stack. I want to create an array named "message" when the time of creating Ticket.
when user click on Create Ticket button we are storing some data like order ID, service, payment, transaction ID, subject along with user Message(user can write briefly about the issue) in MongoDB. once it was stored then admin can reply to that message so we need to create theses are in one document.
I can able to store other fields like order ID, service name, subject but I didn't know how to create array for storing messages.
Please help me.
This is my Ticket Scheema:
const mongoose = require('mongoose');
const User = require('./userScheema');
const TicketScheema=new mongoose.Schema({
subject:{
type:String
},
request:{
type:String
},
orderID:{
type:Number
},
descs:[
{
desc:
{
type:Array,
required:true
}
}
],
name:{
type:String
},
role:{
type:String
},
payment:{
type:String
},
transactionID:{
type:Number
},
status:{
type:String,
default:"Not Answered"
},
date:{
type:Date,
default:Date.now
},
user:{
type:mongoose.Schema.Types.ObjectId,
ref:User,
required:true
}
})
const Ticket=mongoose.model("Ticket",TicketScheema);
module.exports=Ticket;
Express Router:
router.post("/submitTicket",authenticateUser,async(req,res)=>{
try {
let user=req.root_user[0]._id.toString();
let role=req.root_user[0].role.toString();
let name=req.root_user[0].name.toString();
let {subject,request,orderID,desc,payment,transactionID}=req.body;
let resp=await new Ticket({
subject,
request,
orderID,
desc, //here desc is the user message, want to store it as array
payment,
transactionID,
user,
role,
name
})
resp.save();
res.status(201).send(resp)
} catch (error) {
res.status(400).send("Unable to create Ticket")
}
})
Front End:
const createTicket =async()=>{
let resp=await fetch('/submitTicket',{
method:"POST",
headers:{
"Content-Type":"application/json"
},
body:JSON.stringify({
subject,request,orderID,desc:Desc,payment:payment1,transactionID:TransactionID
})
})
if(resp.status==201)
{
alert("Ticket Created")
}
}
Am new to MERN, please help me
CodePudding user response:
You should declare the descs
property as:
descs:[
{
type:String,
required:true
}
],
And then add a new property to the field with:
let resp = new Ticket({
subject,
request,
orderID,
payment,
transactionID,
user,
role,
name,
});
resp.descs.push(desc)
await resp.save()
res.status(201).sendresp)