在流星中更新嵌套集合时,如何为更新路径传递变量 [英] When update nested collection in meteor, how to pass variable for the update path
问题描述
Update a nested collection in meteor is not a problem (and it is described here : Updating a nested property on a collection object with $set)
基本方法:
Collection.update({sel}, {"$set" : {"address.city": "new address"}});
但是如果我想用变量来描述我的路径怎么办?
But what if I want to describe my path with variables ?
这显然不起作用:
var cityName = "NYC";
Collection.update({sel}, {"$set" : {"address." + cityName: "new address"}});
可悲的是,这也不起作用:
Sadly this one does not work either:
var path = "address.NYC";
Collection.update({sel}, {"$set" : {path: "new address"}});
那个也没有:
var object = {"address.NYC": "new address"};
Collection.update({sel}, {"$set" : object});
实际上,它可以工作,但不是我想要的方式.它将完全替换地址"对象,并删除其他属性.
Well, actually, it works, but not the way I want it. It replace entirely the "address" object, removing the other properties.
有什么想法吗?
是否可以在查询部分中选择要更新的字段?
Is there a way to select the field I want to update in the query part ?
推荐答案
It doesn't work because you can't use dynamic keys for object literals in javascript. You need to use bracket notation and build up the object you want to use in the update
. For example:
var city = 'NYC';
var object = {};
object["address." + city] = 'new address';
MyCollectionName.update(idOfObjectToUpdate, {$set: object});
您的最后一个示例应该起作用,假设Collection
实际上是集合的名称,而{sel}
是您要执行的操作的正确选择器.
Your last example should work, assuming Collection
is actually the name of a collection, and {sel}
is the correct selector for what you are trying to do.
这篇关于在流星中更新嵌套集合时,如何为更新路径传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!