0

There is a similar thread @ Mongoose variable key name. However, he goes with another method instead of solving this. The other method is the OR part of my title.

EDIT - IGNORE THIS SECTION, I AM USING THE ALTERNATIVE NOW. Issue now lays with referencing a child's Object ID elsewhere.

I have the following array:

selections: [{
   4433d18d31f3775756ac2a70: "542e91aa31f3775756abccda"},
   {4433d18d31f3775756ac2a71: "542e916c31f3775756abccd8"},
   {4433d18d31f3775756ac2a72: "542e934231f3775756abccdb"
}]

My schema is currently as follows:

selections: {
    <something>: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Selection'
    }
}

In place <something>, is there a way of essentially saying "I don't care what's here"?

ALTERNATIVELY, as this doesn't seem possible after scouring the internet, I can have the following schema:

selections: {
    pid: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Competition.CHILD'
    }
    selection: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Selection'
    }
}

But the issue here is that ObjectID that is being used where <something> is a child schema inside of the schema Competition, and I can't find a way of saying that for the Object ID.

Any advice/help would be great please. Ideally I'd prefer the first solution but I understand it may not be possible. Thanks!

Community
  • 1
  • 1
Gary
  • 395
  • 2
  • 7
  • 24

1 Answers1

1

Use an array of objects with optional (but fixed) keys:

selections: [{
  selection: {type: ObjectId, ref: 'Selection'},
  child: {type: ObjectId, ref: 'Competition.CHILD'}
}]

This will enable you to do better queries, use mongoose population, etc.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Okay thank you, seems a lot simpler this way. To the second part of my question then, how do I define an ObjectId as a child's ObjectID? e.g. my `Competition` schema has the following entry: `selChild: [selChildSchema]`, and the ObjectId for the child would be selChild._id. – Gary Oct 17 '14 at 15:14
  • I would try just `ref: 'Competition.selChild'` but I haven't used such a setup myself so I can't confidently say whether that will actually work with mongoose population (which is the only real purpose of specifying `ref` AFAIK). – Peter Lyons Oct 17 '14 at 16:28
  • `Competition.selChild` didn't work, but you're right it's only used for population from what I can see so it shouldn't actually impact anything. Thanks. – Gary Oct 21 '14 at 10:53