ormsails.jssails-postgresql

Sails ORM: How to know if found or Created in findOrCreate waterline function


I'm using the findOrCreate waterline model function. According to the documentation here, It checks for the existence of the record in the first parameter. If it can't be found, the record in the second parameter is created. Is there any way to know whether it was created or found?

My use-case is to decide if it was conflict ( if the record already exists ) or created in the database.


Solution

  • I would say it is impossible using this "shortcut" function. What I would suggest is to build you own function, which will not be complicated and really straight forward.

    modelName.find(criteriaBasedOnGivenData).exec( function (err, model) {
      if (model)
        return res.ok('found')
      else
      modelName.create(modelWithGivenData).exec (function (err,model) {
        if (model)
          return res.ok('created)
      })
    })