Removing a subdocument from an array using id and user restriction

I have a collection of messages with such objects:

{
    "_id": ...,
    "author": 123,
    "body": "merp",
    "comments": [
        {
            "_id": ...,
            "author": 234,
            "body": "But what about morp?"
        },
        {
            "_id": ...,
            "author": 123,
            "body": "You're out of your element, Donnie!"
        }
    ]
}

I myself create those comment._idwhen they are added. In any case, everything works fine, I learned how to add and remove material from an array of comments, etc.

Unless a comment is deleted, I want to first check if the current user is author. In Meteor, you usually pass the object identifier to the Meteor method, which then checks the object and decides whether it is ok to execute. For instance. To delete a message, my method is as follows:

Meteor.methods({
  deleteMessage: function(messageId) {
    message = Messages.findOne(messageId);

    if(!message) {
      throw new Meteor.Error("not-found");
    }
    if(Meteor.userId() != message.author) {
      throw new Meteor.Error("not-authorized");
    }

    Messages.remove(messageId);
  }
});

, comment? , messageId, commentId, , ? comment _id, ? , , . message, , , _id?

, : , $pull comment _id, , , - , author ?

. Mongo , . , , . , , , , , , . !:)

+4
1

, $pull .update()

Messages.update(
   { 
       "_id": messageId, 
       "comments._id": commentId,
       "comments.author": Meteor.userId()
   },
   { "$pull": { "comments": { "_id": commentId } }
)

"comments._id", , , .

" ", JavaScript, function() sytax . , .update() Meteor.userId() .

$pull , . "" , .

+3

Source: https://habr.com/ru/post/1599436/


All Articles