【问题标题】:How can I assign two types to a specific key in mongoose schema?如何将两种类型分配给猫鼬模式中的特定键?
【发布时间】:2020-10-11 23:24:49
【问题描述】:

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

我想根据我的用例将 ObjectIdstring 保存到 category 值。 mongoose Schema中是否可以为一个键分配两种类型?

如果可能的话,我该如何在给定的架构中实现它。 提前致谢!

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongoose-schema


    【解决方案1】:

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

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

    更多参考:Mongoose Documentation - Schema Types : Mixed

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 1970-01-01
      • 2013-09-22
      • 1970-01-01
      • 2020-12-04
      • 2018-06-21
      • 1970-01-01
      • 2019-10-28
      • 2021-09-25
      相关资源
      最近更新 更多