【问题标题】:How to access and change a specific attribute in a collection?如何访问和更改集合中的特定属性?
【发布时间】:2016-06-20 19:39:15
【问题描述】:

我有一个名为“产品”的集合。我想访问和更改集合中名为“screenShots”的属性。

此代码不适用于我

screenshotsURLS: function(sshots) {
    check(sshots, [String]);
    Products.update({},{$set:{screenShots:sshots}});
    console.log(sshots);
}

当我 console.log 截图时,我可以看到数组存在,但更新功能不起作用

如何将 Product 集合中的 screenShots 属性设置为“screenshotsURLS”函数中传递的任何值?

【问题讨论】:

  • 您想一次更新所有文档吗?
  • @Blaze Sahlzen 不,只有当前文档中的特定元素“screenShots”
  • 您当前的代码将更新它在集合中找到的第一个文档。您应该在第一个{} 中指定一个查询,例如{_id: someId}
  • 您的示例代码是位于服务器端还是客户端?是Meteor method吗?
  • @BlazeSahlzen 你的意思是文档的ID?我怎么得到它?代码在客户端,我将值从会话(我使用你告诉我的方式)传递到服务器端,是的,它是一个 Meteor 方法

标签: meteor meteor-collection2


【解决方案1】:

为此,您必须更新 mongodb 文档。

这是您可以在流星中更新文档的方法。

collectionName.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

在您的情况下,collectionName 是 Products,字段是 screenShots。 所以为了这样做。您的查询将是 截图

Products.update({},{$set:{screenShots:sshots}}) (Be careful this will update all of your doc)

要选择文档更新,请使用类似查询。

Products.update({name:'yourProductName'},{$set:{screenShots:sshots}})

有关更新的更多信息,请查看link

【讨论】:

  • 是否可以只更改 screenShots 属性而不更改其他属性的值?
  • 我的意思是如果我使用 Products.update({},{$set:{screenShots:sshots}}) 会改变集合中其他元素的值吗?
  • 不,Products.update({},{$set:{screenShots:sshots}}) 只会改变screenShots字段的值。
  • 如果您想更改更多文件,只需添加 Products.update({},{$set:{field1 : value1 , field2: value2 : ...}}) 之类的文件
  • 我在实施您的解决方案后更新了我的问题,但仍然无法与我合作,我错过了什么吗?
猜你喜欢
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
  • 2020-04-14
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多