Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

How can I assign two types to a specific key in mongoose schema?


const pendingMenuSchema = new mongoose.Schema({
   
  category: {
    type: [String, mongoose.Schema.ObjectId], // contains existing category id or new category string.
  }
})

I want to save either a ObjectId or a string to the category value depending on my use case. Is it possible to assign two types to a key in mongoose Schema?

If it is possible then how can I implement it in my given schema. Thanking in advance!


Solution

  • For assigning multiple types we can use the Mixed type of Mongoose.

    const mongoose = require("mongoose");
    
    const pendingMenuSchema = new mongoose.Schema({
      category: {
        // type: {}, 
        // OR
        type: mongoose.Schema.Types.Mixed,
      },
    });
    

    For further reference : Mongoose Documentation - Schema Types : Mixed