Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating an object only the first time in mongodb

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}`)
})

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    }   
});

>Solution :

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}`)
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading