I am trying to save the number 3.0 into a schema that expects a double. Unfortunately it seems that Mongo interprets it as an integer and I get a validation failure error.

My validator looks like this:

avgRating: {
  bsonType: 'double',
  minimum: 1,
  maximum: 5
},

My query looks like this:

await db.collection('products').updateOne(
    {_id: productId},
    {
      $set: {
        avgRating: 3.0
      }
    },
);

I have checked with other numbers like 3.00001 or 4.2 and they work fine

2 Answers

0
Matt On Best Solutions

I guess I missed the Double class included in the Node.js driver which causes the number to be treated properly:

const {Double} = require('mongodb');

await db.collection('products').updateOne(
  {_id: productId},
  {
    $set: {
      avgRating: Double(3.0)
    }
  },
);
0
Achraf Almouloudi On

Try changing your validator to the following:

avgRating: {
  bsonType: ["double"],
  minimum: 1,
  maximum: 5
},

I think the lack of [] makes MongoDB treat it as int or something else, causing this behavior.