Mongoose - 如何创建具有固定类型的便携式文档

Mongoose - how to create portable documents with fixed type

假设有一个可以传递给消费者的 JSON 对象,其中 json 对象包含一些变体:

{
    _id: 1
    name:  "my_name",
    type: "my_type",
    my_particulars:  {
      value: 1,
      author: "some author"
    }
}

这样 "type" 值被锁定到 schema/model 是否有满足此要求的既定模式?

在我看来,最好的选择是某种形式的:

var WidgetSchema = new Schema({
  //Name
  name: {type: String, required: true, unique: true},
  type: {type: String, required: true, default: "widget"},
  title: {type: String, required: true },
  description: { type: String, required: true },
  //Status 1: Not Live
  //Status 2: Live
  status: {type: Number, required: true, default: 1}
});

WidgetSchema.virtual('type').set(
function () {
  return false;
});

您可以将其作为虚拟 属性 添加,而不是实际存储类型,它与 JSON 一起返回。类似于:

WidgetSchema.virtual('type').get(function () {
  return 'widget';
});

有了这个定义,您可以通过传递 virtuals 选项指示 mongoose 在 toObject/toJSON 输出中包含虚拟。

// either directly to the method
instanceOfWidget.toJSON({virtuals: true});

// or as a default by setting the option on the schema
WidgetSchema.set('toObject', {virtuals: true});