Hi, I was wondering if this
if(Worlds_Items.findOne({_id:FlowRouter.getParam('item'), itemSlot: "head"})) {
return "Head";
}
else if(Worlds_Items.findOne({_id:FlowRouter.getParam('item'), itemSlot: "torso"})) {
return "Torso";
}
else if(Worlds_Items.findOne({_id:FlowRouter.getParam('item'), itemSlot: "hands"})) {
return "Hands";
}
else if(Worlds_Items.findOne({_id:FlowRouter.getParam('item'), itemSlot: "legs"})) {
return "Legs";
}
else if(Worlds_Items.findOne({_id:FlowRouter.getParam('item'), itemSlot: "feet"})) {
return "Feet";
}
could be converted to a swtich-statement? I read that a lot of if else-statements should be avoided if possible. But since those queries only seem to give out booleans, it seems to be tricky at best. But I was wondering if someone has any solution to this?
many thanks.
if else statements are perfectly fine,
the problem in your code is that it is not DRY (DRY - don’t repeat yourself)
you could do:
const hasItemSlot = (itemSlot) => Worlds_Items.findOne({_id:FlowRouter.getParam('item'), itemSlot}))
// and then
if(hasItemSlot("head")) return "Head"
if(hasItemSlot("torso")) return "Torso"
etc.
but its a bit weird anyway, because Worlds_Items.findOne({_id:FlowRouter.getParam('item')})
will return the same object in every case. its cleaner if you do
const theItem = Worlds_Items.findOne({_id:FlowRouter.getParam('item')})
if(theItem.itemSlot === "head") return "Head"
// etc.
and if you could avoid returning “Head” in uppercase when the value is “head” (lowercase), you could just do
return Worlds_Items.findOne({_id:FlowRouter.getParam('item')})?.itemSlot
4 Likes
const { itemSlot } = Worlds_Items.findOne({ _id:FlowRouter.getParam('item'), itemSlot: {$in: ['head', 'torso', 'hands', 'legs', 'feet' ] } }, { fields: { itemSlot: 1 } })
Also ensure an index for itemSlot on that collection
3 Likes
@paulishca _id field has an unique index, so there is only one doc in the search result. Why we need to create the itemSlot index?
You are 100% right. In this case you don’t even need the second part of the query, just perhaps the “fields”.
Also, if it runs on client side:
Minimongo doesn’t currently have indexes. It’s rare for this to be an issue, since it’s unusual for a client to have enough data that an index is worthwhile.