How do I know if Mongoose upsert created a new document?

I have this code in node.js / express.js:

var User = mongoose.model('User');
var usersRouter = express.Router();
usersRouter.put('/:id', function(req, res) {
    req.body._id = req.params.id;
    var usr = new User(req.body);

    usr.validate(function (err) {
        if (err) {
            res.status(400).json({});
            return;
        }

        var upsertData = usr.toObject();
        delete upsertData._id;

        User.update({_id: usr._id}, upsertData, {upsert: true}, function(err) {
            if (err) {
                res.status(500).json({});
                return;
            }

            res.status(204).json({});
        });
    });
});

It works fine, but I would like to send another review to the client if a new document was created (status 201 with json in the response tag) or already updated (status 204).

Is it possible to distinguish from a callback User.update?

+4
source share
1 answer

Use the third parameter from the callback function:

...
User.update({_id: usr._id}, upsertData, {upsert: true}, function(err, num, n) {
  if (err) {
     res.status(500).json({});
     return;
   }

   if (!n.updatedExisting) { 
       /* new document */
   }

   res.status(204).json({});
});
...

n is an object like this:

{ updatedExisting: false,
  upserted: <ObjectId>,
  n: 1,
  connectionId: 11,
  err: null,
  ok: 1 }

updatedExistingproperty truewhen the document was updated, so it was created earlier. If it is false, it means that a new document was created during this call.

+5
source

All Articles