node.js - 如何根据其他字段添加条件模式?

标签 node.js mongodb mongoose

我有这个结构:

{
    personFullName: String,
    personMobileOS: Number // 1 = IOS, 2 = Android,
    moreDetails: Mixed
}

我想添加基于其他字段的条件架构,如下所示:

if (personMobileOS === 1) { // IOS
    moreDetails = { 
        iosVersion: Number, 
        loveApple: Boolean
    }
} else if (personMobileOS === 2) { // Android
    moreDetails = {
        wantToSell: Boolean,
        wantToSellPrice: Number
        wantToSellCurrency: Number // 1 = Dollar, 2 = Euro, 3 = Pound
    }
}

如您所见,“moreDetails”的模式是有条件的,是否可以在 mongoose 中实现?

最佳答案

不确定是否为时已晚,但我认为您需要的是 mongoose subdocument discriminator .这允许您在子文档上有 2 个不同的架构, Mongoose 将负责架构映射,包括验证。

是的,您需要在此问题中归档的内容是一个长期存在的问题,并且自 mongoose 3.0 以来就已提出要求。现在它是官方的:)

一个带有新的 mongoose 子文档鉴别器的示例:

const eventSchema = new Schema({ message: String },
  { discriminatorKey: 'kind' });

const Event = mongoose.model('Event', eventSchema);

const ClickedEvent = Event.discriminator('Clicked', new Schema({
  element: {
    type: String,
    required: true
  }
}));

const PurchasedEvent = Event.discriminator('Purchased', new Schema({
  product: {
    type: String,
    required: true
  }
}));

Also checkout this blog post了解更多

关于node.js - 如何根据其他字段添加条件模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36999377/

相关文章:

javascript - Express.js 关闭响应

node.js - Aws Ubuntu 上的 NodeJs 应用程序在 ipv6 上运行

node.js - NodeJS-Mongo : Querying the database and gridfs and returning both the document and the image to the user

javascript - Mongoose 查询返回错误,但错误是我正在寻找的结果

node.js - 在同一亚马逊帐户上的存储桶之间移动文件

mongodb - Meteor.js – 基于Session变量的$或mongodb查询

mongodb - 环回 JS : Rename Existing Model

javascript - 如何根据条件设置 Mongoose 模式的默认属性值

mongodb - 推送到 MongooseJS 子文档而不创建重复项

node.js - 什么时候对作业队列使用数据库有意义?