Meteor MongoDB 每个文档数组的设置字段



我在Collection中有一个Documents,该有一个字段是Array(foo(。这是其他subdocumentsArray。我想将每个document中每个subdocument的相同字段(条形图(设置为相同的值。此值来自复选框。

所以。。我的客户端代码是这样的

'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"。有什么想法吗? 我正在为父文档和子文档使用简单架构

谢谢!

尝试传递一个选项来绕过简单架构。它可能缺乏对这个(有点(较新的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');
}
});

旧答案:

由于您说需要为每个文档进行唯一的更新,因此在这种情况下,批量更新听起来是可行的方法。下面是如何在 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...

请注意,如果没有文档,我们会提前退出函数,因为如果没有要处理的操作bulk.execute()会引发异常。

如果你的数据在数组上每个条目的$set中都有不同的数据,我认为你需要在服务器端有一个循环。

Mongo 有批量操作,但我不知道您是否可以使用
我使用rawCollection()访问聚合Collection.rawCollection().XXXXX调用它们,它对我来说效果很好。也许使用批量操作。

最新更新