How is the field of growth in mango?

I have the following Mongo DB document structure:

{
  _id: channelId, 
  title: channelTitle,
  pubDate: channelPubdate, 
  items: 
  [
    {
      title: newsTitle,
      desc: newsDescription, 
      link: newsLink, 
      pubDate: Date, 
      clicks: 0
    },
    {/*One more*/},
    {/*...*/}
  ] 
}

      

I am having problems increasing the "clicks" field in a collection (updating a document field embedded in an array).

I tried this in my event handler (client):

News.update({ _id : Session.get("channelId"), "items.link" : this.link },
  { $inc: { "items.clicks": 1 } }
);

      

But this gives an error: Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]

Then I tried using the server method:

Meteor.methods({
    incClicks: function(id, news) 
    {
      News.update({ _id : id, "items.link" : news.link }, 
        { $inc : { "items.clicks": 1 } }
      );
    }
});

      

However, another exception: Exception while invoking method 'incClicks' MongoError: can't append to array using string field name: clicks

What would be the correct Mongolian query for this action?

+3


source to share


1 answer


As the error points out, on the client, you can only update with a simple selector _id

. I would recommend using the method with a slight modification to your code:

Meteor.methods({
  incClicks: function(id, news) {
    check(id, String);
    check(news, Match.ObjectIncluding({link: String}));

    News.update(
      {_id: id, 'items.link': news.link},
      {$inc: {'items.$.clicks': 1}}
    );
  }
});

      



Here we use an operator $

to update a specific inline document. See the docs for details .

+3


source







All Articles