1

I want to insert to new field and data in existing document, if there is no data in it.

 if (repoData.detailViewCounter == undefined) {
        console.log('create 0')
        Repo.findOneAndUpdate({
          'owner.login': userId,
          'name': pageId
        }, {
            detailViewCounter: 0
          },
          {new: true, upsert: true})
      }

So When condition like this, and there is no detailViewCounter field, insert new field with number 0.

{
  'owner.login': userId,
  'name': pageId
}

But When I run this code and check the MongoDB Compass, there is still no data. And I also create repo schema detailViewCounter with type:Number

writingdeveloper
  • 984
  • 2
  • 21
  • 46

1 Answers1

1
  • change in option upsert: false
  • one major problem is field name "owner.login" this is causing the issue, this will search in object owner: { login: userId } but in actual we have string "owner.login", so this is not able to find any matching document, and this will not update record.
  • you can check after removing condition on field owner.login, it will work
Repo.findOneAndUpdate({
    'name': pageId
  }, 
  { detailViewCounter: 0 },
  { new: true, upsert: false }
)

Look at MongoDB restriction on field names, and good question in SO.

turivishal
  • 34,368
  • 7
  • 36
  • 59