I'm making an app where a user makes a safe by going to /mysafe. But i only want to create it the first time when he goes there and for the next time when he goes to /mysafe it should redirect to /mysafe/theidofit.
See my app.js
app.get('/mysafe',async (req,res)=> {
const safe=new Safe()
safe.author=req.user._id
safe.save()
res.redirect(`/mysafe/${safe._id}`)
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I tried adding a middleware but in my user schema i dont have a safe defined.Do i need to define it or can i do it without it?
const UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true
}
});
CodePudding user response:
app.get('/mysafe', async (req,res)=> {
let safe = await Safe.findOne({author: req.user._id});
if (!safe) {
safe = new Safe()
safe.author=req.user._id
safe.save()
}
res.redirect(`/mysafe/${safe._id}`)
})