提问者:小点点

如何在mongoose模式中将两种类型分配给一个特定的键?


null

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

null

根据我的用例,我希望保存一个ObjectId或一个字符串到category值。在mongoose模式中,有可能为一个键分配两种类型吗?

如果有可能,那么我如何在给定的模式中实现它。提前感谢!


共1个答案

匿名用户

为了分配多个类型,我们可以使用mogoosemixed类型。

const mongoose = require("mongoose");

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

更多参考:Mongoose文档-模式类型:Mixed