Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

meteor - How to increment a field in mongodb?

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 have troubles incrementing the "clicks" field in the Collection (updating the field of a document embedded in an array).

I tried this in an event handler (client):

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

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

I then tried via a server method:

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

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

What would be a correct Mongo request for this action?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the error indicates, on the client you can only perform an update with a simple _id selector. I'd recommend using a 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 are using the $ operator to update the specific embedded document. See the docs for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...