Home > OS >  MongoServerError: Cannot create field 'count' in element
MongoServerError: Cannot create field 'count' in element

Time:09-26

When the database matches the below value then I want to increase the count by 1.

const inr = await Postproduct.updateOne({"uid":123456,"userclick.email":"[email protected]"},{$inc: { "userclick.count": 1}})

But right now I'm getting the following error while doing so. Error

And this is my database

MongoDB Output

Kindly help me with the same. What I want to do is every time the user clicks the button. I want the count to increase by 1.

CodePudding user response:

You can set default value of count to zero. like this :

userClicks:[{
count:{type:Number,default:0,},
email:String,
satisfy:String,
amount:Number,
          }]

CodePudding user response:

Since userclick is an array, you will need to use an array operator for updating just the one element.

In this case, since the query uniquely identifies one element, you can use the $ positional operator, like:

await Postproduct.updateOne(
    {"uid":123456,"userclick.email":"[email protected]"},
    {$inc: { "userclick.$.count": 1}}
)
  • Related