【问题标题】:having difficulty inserting an array of subrecords using $push, getting internal server error使用 $push 插入子记录数组时遇到困难,出现内部服务器错误
【发布时间】:2013-12-18 03:05:00
【问题描述】:

我尝试在我的数据库中创建以下记录:

{
    "userid":
    "songs":[
         {
              "title":
              "artist":
         }
         {
              "title":
              "artist":
         }
    ]

}

一个用户下可以有多首歌曲。我不确定插入具有多个子记录的记录的正确语法。我尝试使用:

Links.insert({userid: "user1", $push: {songs: {"song1","artist1"}}});

我尝试使用另一种替代方法,即首先创建仅包含用户 ID 字段的记录,然后进行更新以将歌曲推送到记录中。但是,当我执行以下操作时出现以下错误:

Links.update({_id: Links.findOne({userid: "user1"})._id, $push: {songs:{"song1","artist1"}}});

未捕获的错误:不允许。不受信任的代码只能按 ID 更新文档。 [403]

我很困惑,因为我使用 _id 字段来更新记录。有关如何解决此问题的任何建议?

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    您的 mongo 查询错误。这些应该可以工作(未经测试):

    插入

    Links.insert({ 
        userid : "user1", 
        songs : [ 
            { title : "song1", artist : "artist" }, 
            ... 
        ] 
    });
    

    您不需要在插入命令中推送数组。

    更新

    Links.update({
        _id : Links.findOne({ userid : "user1" })._id
    },
    {
        "$push" : { title : "song1", artist : "artist" }
    });
    

    请注意,更新查询有两个对象传递给它,一个是selector,第二个是要应用的modifier

    http://docs.meteor.com/#selectors

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-03
      • 2020-03-02
      • 2015-06-18
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      相关资源
      最近更新 更多