0

I am encountering an issue with findOneAndUpdate operation on nodejs mongodb library, where I cannot tell if an update was done or not.

I wrote a query that can successfully update the document as expected, but value:null was returned after the update. Ultimately, I would like to distinguish between 3 cases:

  1. Document found, cannot be updated
  2. Document found and successfully updated
  3. Document not found

    const result = await collection.findOneAndUpdate(
      { caseId: caseId, list: {$ne: userId}, $expr: {$lt:[ {$size: '$list'}, 'maxLength']} },
      { $push: {assignees: userId}})
    return result.value;
    

A little explaination on the query:

I want to append userId to the list field of a document if

  • caseId matches,
  • the user is not currently in the list,
  • the size of the list is smaller than the maxLength
chakwok
  • 980
  • 8
  • 21
  • 1
    Possible duplicate of [Mongoose: findOneAndUpdate doesn't return updated document](https://stackoverflow.com/questions/32811510/mongoose-findoneandupdate-doesnt-return-updated-document) – noChance May 20 '19 at 08:18
  • This isn't hidden knowledge. Read the documentation: https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate – jakedipity May 20 '19 at 08:49
  • As I mentioned nothing is returned in my case, neither the original document nor the updated documents. Having the {returnOriginal: false} won't help in this case. The solution from that post doesn't help – chakwok May 20 '19 at 08:49
  • @Andyk. If nothing is returned then your query isn't matching anything. – jakedipity May 20 '19 at 08:51
  • @JacobHull It does match something. When I check the database directly, the new element is appended the first time I run this query. To my surprise, adding a $set operator solved my problem (see answer below for code). I am not so sure why tho – chakwok May 20 '19 at 09:43

2 Answers2

0

Adding {new: true} will return updated document in result

const result = await collection.findOneAndUpdate(
  { caseId: caseId, list: {$ne: userId}, $expr: {$lt:[ {$size: '$list'}, 'maxLength']} },
  { $push: {assignees: userId}},
{new: true}
)

Amol B Jamkar
  • 1,227
  • 10
  • 19
0

Adding a $set update operator solved my problem.

It seems that the $push update operator does not trigger an update notification to nodejs. The new element is appended to the collection, but the response treated it as no update done.

const result = await collection.findOneAndUpdate(
  { caseId: caseId, list: {$ne: userId}, $expr: {$lt:[ {$size: '$list'}, 'maxLength']} },
  { $push: {assignees: userId}, $set: {caseId: caseId}})
return result.value;
chakwok
  • 980
  • 8
  • 21