![](/img/trans.png)
[英]Return contents of one field (an array) from Mongodb document in Meteor
[英]Meteor MongoDB Setting field of array per document
我在一个Collection
中有一个Documents
,其中一个字段是一个Array
(foo)。 这是其他subdocuments
的Array
。 我想将每个subdocument
中的每个子document
的相同字段(栏)设置为相同的值。 该值来自复选框。
所以..我的客户端代码类似于
'click #checkAll'(e, template) {
const target = e.target;
const checked = $(target).prop('checked');
//Call Server Method to update list of Docs
const docIds = getIds();
Meteor.call('updateAllSubDocs', docIds, checked);
}
我尝试使用https://docs.mongodb.com/manual/reference/operator/update/positional-all/#positional-update-all
并为我的服务器辅助方法提出了以下内容。
'updateAllSubDocs'(ids, checked) {
Items.update({ _id: { $in: ids } }, { $set: { "foo.$[].bar": bar } },
{ multi: true }, function (err, result) {
if (err) {
throw new Meteor.Error('error updating');
}
});
}
但这会引发错误“架构不允许 foo.$[].bar”。 有任何想法吗? 我对父文档和子文档都使用 SimpleSchema
谢谢!
如果您的数据在数组中的每个条目的 $set 中有不同的数据,我认为您需要在服务器端进行循环。
Mongo 有 Bulk 操作,但我不知道你是否可以使用Collection.rawCollection().XXXXX
调用它们
我使用rawCollection()
来访问聚合,它对我来说很好。 也许与批量操作一起工作。
尝试传递一个选项来绕过简单模式。 它可能缺乏对这个(有点)新的 Mongo 功能的支持。
bypassCollection2
例子:
Items.update({ _id: { $in: ids } }, { $set: { "foo.$[].bar": bar } },
{ multi: true, bypassCollection2: true }, function (err, result) {
if (err) {
throw new Meteor.Error('error updating');
}
});
老答案:
由于您说您需要为每个文档进行唯一更新,因此在这种情况下,批量更新是 go 的方式。 下面是如何在 Meteor 中执行此操作的示例。
if (docsToUpdate.length < 1) return
const bulk = MyCollection.rawCollection().initializeUnorderedBulkOp()
for (const myDoc of docsToUpdate) {
bulk.find({ _id: myDoc._id }).updateOne({ $set: update })
}
Promise.await(bulk.execute()) // or use regular await if you want...
请注意,如果没有文档,我们会提前退出 function,因为如果没有要处理的操作, bulk.execute()
会引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.