在meteor中更新嵌套集合时,如何为更新路径传递变量 [英] When update nested collection in meteor, how to pass variable for the update path

查看:16
本文介绍了在meteor中更新嵌套集合时,如何为更新路径传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在meteor 中更新嵌套集合不是问题(这里描述了:使用 $set 更新集合对象上的嵌套属性)

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 ?

推荐答案

它不起作用,因为你不能使用 javascript 中对象字面量的动态键.您需要使用括号表示法并在 update 中构建要使用的对象.例如:

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.

这篇关于在meteor中更新嵌套集合时,如何为更新路径传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆