如何添加基于其他领域的条件模式?
我有这样的结构:
{ 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中实现这一点?
不知道这是为时已晚,但我认为你需要的是mongoosesubdocument鉴别 。 这允许你在子文档上有两个不同的模式,mongoose会照顾模式映射,包括validation。
是的,你需要在这个问题上存档是一个长期存在的问题,并要求从mongoose3.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 } }));
也检查这个博客文章的更多细节
- 在NodeJS中dynamic构buildMongoDB查询
- 使用mongodbembeddedJson数据
- Javascript商店作为一个variables逗号分隔的string为mongoDB
- 如何知道mongodb查询有多less匹配
- Mongoose:CastError:强制转换为ObjectId的path“_id”的值为“”
- Mongoosastic – 将ObjectId索引到弹性search中
- mongoose得不到工作(SchemaType#get(fn))
- Sails.js:模型本身的一对多关系
- 当modelObject从数据库本身获得时,modelObject.save()是否只更新现有的数据库文档?