coffeemeup
coffeemeup

Reputation: 13

Can't $push a new array to document in Meteor Collection

I've been learning Meteor for about 3 weeks, and am still trying to wrap my head around updating/querying collections. I'm trying to build a Slack clone, and created the following collection with one set of fixture documents:

Conversations.insert({
    channel: "#defaultChannel",
    createdBy: "coffeemeup",
    timestamp: new Date(),
    followers: ["username1", "username2"],
    entries: [
    {
      message: "this is a message #1",
      postedTime: new Date(),
      author: "coffeemeup"
    }]
});

I'm trying to insert another document into the entries array using the code below. But not only does that not work, it throws a "Mutating the [[Prototype]] of an object will cause your code to run very slowly..." error. I'd really appreciate some help!

Conversations.update({
    channel: "#defaultChannel"
}, {
    $push: {
        entries: {
            message: newMessage,
            postedTime: new Date(),
            author: "coffeemeup"
        }
    }
});

Also, I would love to hear suggestions on how to better structure/design this database to build a Slack clone.

Upvotes: 1

Views: 1186

Answers (1)

Matthias A. Eckhart
Matthias A. Eckhart

Reputation: 5156

If you want to run update operations on clients, you need to use the _id field. Otherwise you will get this error:

Error: Not permitted. Untrusted code may only update documents by ID. [403]

As a result, get the document first and subsequently use the document's _id to run the update query.

For example:

var conversation = Conversations.findOne({
    "channel": "#defaultChannel"
});

Conversations.update({
    _id: conversation._id
}, {
    $push: {
        entries: {
            message: "newMessage",
            postedTime: new Date(),
            author: "coffeemeup"
        }
    }
});

Here is what the updated conversation document looks like:

{
   "_id": "wGixGJgoM6fk57mtN",
   "channel": "#defaultChannel",
   "createdBy": "coffeemeup",
   "timestamp": "2015-07-27T19:25:52.842Z",
   "followers": [
      "username1",
      "username2"
   ],
   "entries": [
      {
         "message": "this is a message #1",
         "postedTime": "2015-07-27T19:25:52.842Z",
         "author": "coffeemeup"
      },
      {
         "message": "newMessage",
         "postedTime": "2015-07-27T19:27:54.930Z",
         "author": "coffeemeup"
      }
   ]
}

Upvotes: 1

Related Questions