-1

Is there a way to write this part better?

'update': function (req, res) {
    var item = req.body.item;
    var tags = [];
    tag.find(function (err, _tags) {
        tags = _tags;
        post.update({ '_id': item._id }, { $set: { Text: item.Text } }, function (e1, r1) {
            post.update({ '_id': item._id }, { $pullAll: { Tags: tags } }, function (e2, r2) { 
                post.update({ '_id': item._id }, { $pushAll: { Tags: item.Tags } }, function (e3, r3) {
                    if (r3 === 1) {
                        res.json(true);
                    }
                });
            });
        });
    });
}

Post has array of tags, and i want to update tags, i get all tags, and $pullAll them to empty the array of item tags, then $pushAll to fill again, i don't want to append new tags, because it's an update method, above code works as expected, but guess it's a bit incorrect

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • 1
    Wouldn't a single `{ $set: { Text: item.Text, Tags: item.Tags } }` do the same thing? – JohnnyHK Sep 27 '14 at 13:50
  • you are right, answer and i will mark, i think i asked not correct way, can you tell how to make multiple operators in 1 line or i should make new question? – Medet Tleukabiluly Sep 27 '14 at 14:11
  • See this other post for your follow-up question: http://stackoverflow.com/questions/9823140/multiple-mongo-update-operator-in-a-single-statement – JohnnyHK Sep 28 '14 at 14:05

1 Answers1

0

Assuming you're trying to replace the existing Tags with the new set, you can simplify that to:

'update': function (req, res) {
    var item = req.body.item;
    post.update({ '_id': item._id },
        { $set: { Text: item.Text, Tags: item.Tags } },
        function (e1, r1) {
            if (r1 === 1) {
                res.json(true);
            }
        }
    );
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471