0

What would be the best approach to only POST data into MongoDB if it doesn't exist in the table? hash would be the unique field for searching, this field is also indexed.

router.post('/', async (req, res) => {
  try{ 
    var id = null
    const keywords = await db.dbConn('kw_data');
    await keywords.insertOne({
      result: req.body,
      added: new Date(),
      modified: new Date(),
      hash: req.body.hash
    }).then(resp => {
      id = resp.insertedId
    })
    var data = {}
    data = await keywords.findOne({_id: id});
    res.status(201).send(data);
  }
  catch(e) {
    res.status(400).send(e);
    res.status(404).send(e);
    res.status(500).send(e); 
  }
})
Jan
  • 653
  • 1
  • 7
  • 22
  • Possible duplicate of [mongodb: insert if not exists](https://stackoverflow.com/questions/2801008/mongodb-insert-if-not-exists) – Yan Foto Apr 19 '19 at 10:27

2 Answers2

1

You can use

await keywords.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
   }
);

and set

upsert:true

So you are inserting data and database will itself know if data is created it will get updated and if it does not exist the database will create it for you

0

I think I have got it by just doing a check on the hash, but not sure if this is the best approach, correct me if I'm wrong...

router.post('/sug', async (req, res) => {
  try{ 
    var id = null
    const keywords = await db.dbConn('kw_sug');
    check = await keywords.findOne({hash: req.body.hash});
    if(check === null){
      await keywords.insertOne({
        results: req.body,
        added: new Date(),
        modified: new Date(),
        hash: req.body.hash
      }).then(resp => {
        id = resp.insertedId
      })
      var data = {}
      data = await keywords.findOne({_id: id});
      res.status(201).send(data);
    }else{
      res.status(201).send('duplicated');
    }
  }
  catch(e) {
    res.status(400).send(e);
    res.status(404).send(e);
    res.status(500).send(e); 
  }
})
Jan
  • 653
  • 1
  • 7
  • 22