【问题标题】:How do I update a collection using multiple _id's?如何使用多个 _id 更新集合?
【发布时间】:2017-09-10 20:41:33
【问题描述】:

我正在尝试更新基于多个 _id 的集合。

我通过 Session.get() 以数组格式接收 _id,如下所示:

 var selectedID = Session.get('selectedItemIDSet');

 console.log("selectedID array contents are: "+selectedID); 

上面的代码确保selectedID 数组存在并产生:

selectedID数组内容为:LZJKA8S3wYNwHakzE,ikrbCDuttHrwkEcuv

下面的查询:

buyList.find({_id:{ "$in": selectedID} }).fetch(); 

成功生成两个对象!

现在遇到问题,如何使用这两个 _id 更新集合

我已尝试使用以下代码:

var PostedArray = [{PostedBy: Meteor.user()._id }];
buyList.update(_id: selectedID, {$set: {wishListArray: PostedArray} });

...但收到错误消息:未捕获的错误:Mongo 选择器不能是数组。(...)

任何帮助将不胜感激。

【问题讨论】:

    标签: mongodb meteor mongodb-query


    【解决方案1】:

    update 中使用与 find 相同的选择器 + 指定 multi: true 选项:

    buyList.update({ // selector
      _id: {
        "$in": selectedID
      }
    }, { // modifier
      $set: {
        wishListArray: PostedArray
      }
    }, { // options
      multi: true
    });
    

    请注意,您的 2 个文档将使用相同的修饰符进行更新。

    【讨论】:

    • 您还需要在末尾添加{multi: true} 以确保更新了多个文档。所以最终的代码是buyList.update({ _id: { "$in": selectedID }}, { $set: { wishListArray: PostedArray }}, { multi: true });
    • @ghybs 谢谢大家。按照您的建议,我收到此错误消息:未捕获。 errorClass {错误:403,原因:“不允许。不受信任的代码只能按 ID 更新文档。” , details: undefined, message: "Not allowed. Untrusted code may only update documents by ID. [403]", errorType: "Meteor.Error"}
    • @SirBT 你在哪里执行你的代码?你还有insecure 包吗?
    • @ghybs 我在 chrome 浏览器控制台上执行代码,假设相当于在客户端运行它。不,我没有不安全的包裹。我不久前删除了它。
    猜你喜欢
    • 2020-05-10
    • 2020-02-07
    • 1970-01-01
    • 2018-09-09
    • 2018-06-02
    • 2019-06-27
    • 1970-01-01
    • 2016-03-26
    • 2021-08-16
    相关资源
    最近更新 更多