Search code examples
mongodb

In mongo database, when saving NaN for few JSON properties converted to null automatically


I need to store value as NaN for few JSON properties. When I save it Mongodb automatically converted to null. how to stop this behavior.

Code snippet: Mongo db Model class :

import mongoose, { Schema } from "mongoose";

const prodSchema = new Schema({
  productName: String,
  oppId: mongoose.Schema.Types.ObjectId,

// I am saving in fron-end as NaN type but in database its getting saved as null
  isNaNOrNot: String,  
 
  createdById: String,
  createdBy: String,
}, { strict: false} );

export const Product = mongoose.model("Product", productSchema);

Solution

  • NaN is not a valid BSON Type, Ref : Valid BSON Types. That is why it is converted to null on storing in database.

    Since the isNaNOrNot field is already of type String, if you wish to store NaN as a value, you should store it as the string "NaN"