Store data as JSON in MongoDB

I am building a digital-card generator app in node.js. In this I want to store the card data as JSON in the MongoDB database. I am using mongoose ODM. but I think mongoose does not support the data-type of Json or object.

The card schema:

const digitalCardSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    data: {
      type: String,
    },
  },
  {
    timestamps: true,
  }
);

I want to strore the field data as JSON object from the above schema. How can I do that?

Hi,

Just add type: Object:

const digitalCardSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    data: {
      type: Object,
    },
  },
  {
    timestamps: true,
  }
);

You can also additionally specify nested properties if you want:

const digitalCardSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    data: {
      card_number: String,
      holder_name: String,
      balance: Number,
      ...
    },
  },
  {
    timestamps: true,
  }
);
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.