Mongoose Middleware - Determine whether to save new or update existing document
I believe your desired result could be achieved by using the findOneAndUpdate
method, with the upsert
option. This will insert a new record if one does not exist, or update the existing record if a match is found.
UserAnswer.findOneAndUpdate({ userId: userId, surveyId: surveyId, timestamp: { $gte: startOfToday } }, {userId: userId, surveyId: surveyId, score: score, timestamp: Date.now()}, {upsert: true, sort: {timestamp: -1}}, function(err, doc) { //do something with the results });