代码之家  ›  专栏  ›  技术社区  ›  Ibad Shaikh

如何为mongose模式中的特定键分配两种类型?

  •  0
  • Ibad Shaikh  · 技术社区  · 4 年前

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

    我想救一个 对象ID 或a 一串 类别 值取决于我的用例。 在mongose Schema中,是否可以为一个键分配两种类型?

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

    0 回复  |  直到 4 年前
        1
  •  4
  •   Sachin Kumar Rajput    4 年前

    为了分配多种类型,我们可以使用 Mixed 类型 Mongoose .

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

    进一步参考: Mongoose Documentation - Schema Types : Mixed