Meteor collection2 array with Strings and Object

2019-07-24 05:47发布

问题:

i'm using Meteor with collection2 and I have an array that looks like this:

productTypes = ["string1", "string2", "string3", {Other: "test"}]

Essentially there will be anywhere from 0 to 7 strings in the array, and Other: 'Test' may or may not be present

So i'm trying to make a schema that handles that case. Is there a way to tell it that there will be strings and an object within an array?

I've tried

const residentSchema = new SimpleSchema({
  productTypes: {type: [String, Object], optional: true, blackbox: true},
})

But that obviously won't work because it's expecting one String and one Object. Does anyone know how I can make this work? Thanks in advance

Edit:

I am now storing it with this format:

productTypes = { list: ["string1", "string2", "string3"], Other: "test"}

but when I add a schema like this:

const productTypeSchema = new SimpleSchema({
  list: {type: Array},
  other: {type: String}
})

const residentSchema = new SimpleSchema({
  productTypes: {type: productTypeSchema},
})

My App crashes. When I remove the line list: {type: Array} it is fine.

Is Array now allowed as a value of SimpleSchema?

回答1:

With collection2 you can have an array of primitives or an array of objects but not a mixed array. Just from a modeling pov it's really messy.

I suggest you refactor your array, instead of:

productTypes = ["string1", "string2", "string3", {Other: "test"}]

for example:

productTypes = { list: ["string1", "string2", "string3"], Other: "test"}