2

I've got a document structure like this:

Content {
  _id: "mongoId"
  Title: "Test",
  Age: "5",
  Peers: [{uniquePeer: "1", Name: "Testy Test", lastModified: "Never"}, {uniquePeer: "2", Name: "Test Tester", lastModified: "Never"}]

}

So Peers is an array that has a unique identifier. How can I update the lastModified of one of the sets in the array? According to mongodb I can only update a document using the document's unique ID, but that's at the top level. How can I say update this lastModified field in this set of Peers with a uniquePeer of 1 in this document?

Edit:

Content.update({"_id" : "mongoId", "Peers.uniquePeer" : "1"},{$set : {"Peers.$.lastModified" : "Now"}})

I still get a "Not permitted. Untrusted code may only update documents by ID."

3
  • I've added an update with the what you say is a duplicate. I can't seem to get it to work for mine. Commented Aug 3, 2015 at 20:41
  • In my code, my uniquePeer isn't an integer, it's a guid that has letters and numbers so I have to put a quote around it. Commented Aug 3, 2015 at 20:45
  • You're right. Thanks. I've updated it. Commented Aug 3, 2015 at 21:08

1 Answer 1

4

See the docs for updating an array. Your code should look something like:

server

Meteor.methods({
  'content.update.lastModified': function(contentId, peerId) {
    check(contentId, String);
    check(peerId, String);

    var selector = {_id : id, 'Peers.uniquePeer': peerId};
    var modifier = {$set: {'Peers.$.lastModified': 'Now'}};
    Content.update(selector, modifier);
  }
})

client

Meteor.call('content.update.lastModified', contentId, peerId);

Note that this kind of operation needs to take place in a server-defined method because, as you found out, you can only update docs by id on the client.

Sign up to request clarification or add additional context in comments.

3 Comments

Does the string 'Now' magically get transformed by mongo to new Date()?
That would be cool, but no, I was just following his example.
That was my initial thought - "Did mongo just introduce a new trick?" So Joshua, you probably want new Date() there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.