我必须有不同的集合、字符和灵魂,它们共享许多相同的属性,并在相同的上下文中使用。这意味着每次我想对这些集合进行读/写时,我都必须执行“类型检查”,然后按下面所示复制代码两次。有什么办法可以实现
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 }})发布于 2014-09-08 09:38:29
只需在文档中添加一个type (/class/collection)字段:
Character.prototype.type = ->
Character
Soul.prototype.type = ->
Soul
...
target.type.update ...https://stackoverflow.com/questions/25720733
复制相似问题