我有不同的集合角色和灵魂,它们共享许多相同的属性并在同一个上下文中使用。这意味着每次我想读/写这些集合时,我都必须进行“类型检查”,然后复制代码两次,如下所示。有没有办法完成
Polymorphic.update()..
而不是
(Pseudocode)
if target.is(Character)
same logic..
Character.update(same query/fields)..
else
same logic..
Soul.update(same query/fields)..
完整的代码
#
# Adds a new condition instance to target
#
addCondition: (effect, target) ->
name = effect.name
maxDuration = effect.maxDuration
curDuration = if effect.curDuration then effect.curDuration else maxDuration
maxStack = effect.maxStack
curStack = if effect.curStack then effect.curStack else 1
stackable = if maxStack then true else false
if target.location <--- This is my type check, only the Character collection has a location field
character = Characters.findOne({_id: target._id, 'conditions.name': name}, { fields: {'conditions.$': 1} })
if character then existingCondition = character.conditions[0]
if existingCondition and stackable
# Apply additional stack and refresh duration
if existingCondition.curStack < existingCondition.maxStack
Characters.update({ _id: target._id, 'conditions.name': name }, { $inc: { 'conditions.$.curStack': 1 }, $set: { 'conditions.$.curDuration': maxDuration } })
else
Characters.update({ _id: target._id, 'conditions.name': name }, { $set: { 'conditions.$.curDuration': maxDuration } })
else if existingCondition and !stackable
Characters.update({ _id: target._id, 'conditions.name': name }, { $set: { 'conditions.$.curDuration': maxDuration } })
else
effect = _.extend(effect, {curDuration: curDuration, curStack: curStack})
Characters.update(_id: target._id, {$addToSet: { conditions: effect }})
else
soul = Souls.findOne({_id: target._id, 'conditions.name': name}, { fields: {'conditions.$': 1} })
if soul then existingCondition = soul.conditions[0]
if existingCondition and stackable
# Apply additional stack and refresh duration
if existingCondition.curStack < existingCondition.maxStack
Souls.update({ _id: target._id, 'conditions.name': name }, { $inc: { 'conditions.$.curStack': 1 }, $set: { 'conditions.$.curDuration': maxDuration } })
else
Souls.update({ _id: target._id, 'conditions.name': name }, { $set: { 'conditions.$.curDuration': maxDuration } })
else if existingCondition and !stackable
Souls.update({ _id: target._id, 'conditions.name': name }, { $set: { 'conditions.$.curDuration': maxDuration } })
else
effect = _.extend(effect, {curDuration: curDuration, curStack: curStack})
Souls.update(_id: target._id, {$addToSet: { conditions: effect }})
答案 0 :(得分:1)
只需在您的文档中添加type
(/ class
/ collection
)字段:
Character.prototype.type = ->
Character
Soul.prototype.type = ->
Soul
...
target.type.update ...