Ibad Shaikh
Ibad Shaikh

Reputation: 3516

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!

Upvotes: 2

Views: 3000

Answers (1)

Sachin Kumar Rajput
Sachin Kumar Rajput

Reputation: 91

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

Upvotes: 4

Related Questions