Search code examples
javascriptmongodb

Mongodb findOneAndUpdate - check if new document added, or just updated


I have the following code which is finding and updating an employee-store record (if it exists, otherwise it creates one).

I have lots of employees in different stores, and they can choose to change store at any point (as long as the location is in America)

Below is my code so far:

    employee = await this.employeeStoreModel.findOneAndUpdate(
      { employee: employeeRecord._id, location: "America" },
      {
        employee: employeeRecord._id,
        store: employeeRecord.store,
        location: "America",
      },
      { new: true, upsert: true }
    );

This works correctly, however I am trying to return some messages from this based on what is being updated. It could be any of the following messages:

  • If it's a completely new employee-store record being added, then return "{{StoreID}} has a new employee - {{EmployeeID}}"
  • If it's a change of store on an existing employee-store record, then return "{{EmployeeID}} has changed from {{old StoreID}} to {{new StoreID}}"

Is this possible to do? Can anyone guide me on how I could start this?


Solution

  • In the Options field,

    includeResultMetadata: true,
    

    You must add the parameter.

    The result will be as in the example below.

    { response:
         { n: 1,
           updatedExisting: false,
           upserted: 5e6a9e5ec6e44398ae2ac16a },
        value:
         { _id: 5e6a9e5ec6e44398ae2ac16a,
           name: 'Will Riker',
           __v: 0,
           age: 29 },
        ok: 1 }
    

    Depending on whether there is an update or insert in the updatedExisting field, you can return any message you want.