findOneAndUpdate Trigger doesn't return updated document

I’m having an issue where findOneAndUpdate doesn’t return a document in my Trigger. findOneAndUpdate is updating the query document correctly but I need the updated document _id returned to add to a different document.

The lines below with <---- are referring to my issue.

// document info
const currManagerId = changeEvent.documentKey._id;
const currManagerDoc = changeEvent.fullDocument;

// ---------- add manager to season

query = { 'leagueId' : currManagerDoc.leagueId, 'year' : currManagerDoc.years[0] };
update = {
  '$push' : { 'managers' : currManagerId },
  '$inc' : { 'info.numManagers' : 1 }
};
options = { 'upsert': false, 'returnNewDocument' : true };
const currSeasonDoc = seasons.findOneAndUpdate(query, update); // <---- TODO not returning document... but updating document fields correctly
console.log(currSeasonDoc._id); // <---- undefined...

// ---------- add season to manager

query = { 'leagueId' : currManagerDoc.leagueId, '_id' : currManagerId };
update = {
  '$push' : { 'seasons' : currSeasonDoc._id }, // <---- TODO field ignored since currSeasonDoc._id is undefined
  '$inc' : { 'info.numSeasons' : 1 } // <---- this field gets updated correctly
};
options = { 'upsert': false, 'returnNewDocument' : false };
managers.findOneAndUpdate(query, update, options);

Any tips on what might be wrong here? Or if there is a different function that is better suited for this application? Thanks.

Hi,

I haven’t used triggers, and this is a side comment, but doesn’t seasons.findOneAndUpdate(query, update); return a promise?

Then the next line(s) will log undefined as this is asynchronous code.

You need to use .then or pass a callback imho.

I’m a little confused about some of the documentation because here it says that findOneAndUpdate returns a document:

“Returns: Returns either the original document or, if returnNewDocument: true , the updated document.”

but here it returns a Promise. I tried adding a callback:

seasons.findOneAndUpdate(query, update, {}, function (error, result) {
  console.log('in'); <--- doesn't get displayed
  if (!error) {
    console.log('Operation completed successfully: ${result.ok}');
    console.log(result.value);
  } else {
    console.log('An error occurred: ${error}');
  }
});
console.log('out'); // <---- gets displayed

When running this I see that ‘out’ is printed but ‘in’ is not. So it doesn’t seem like the callback function is being executed…

Hey,

Yes MongoDB can be daunting.

↑↑↑ That’s the docs for the MongoDB Shell. It looks like you’re using the MongoDB Driver, i.e ↓↓↓:

1 Like

Thanks for the help. I looked into asynchronous functions regarding the driver and it makes sense now.

1 Like