N
N
NodeBegginer2014-08-21 17:45:36
MongoDB
NodeBegginer, 2014-08-21 17:45:36

Nodejs Mongoose update of two documents?

Good day. I recently started using Node Js and MongoDb. Let's say there is a standard system of posts, users and likes for posts. The Post document contains the favoriteCount field, the User document contains the favorites array, which contains the id of the liked post. You need to make sure that after liking a post, the post id is written to the array of the User document, and the favoriteCount field of the Post document is incremented or decremented. I wrote the code below. Is this the correct approach? What are your comments/suggestions?

exports.addFavorite = function(req, res) {
    var postId = req.body.id;
    if (req.user) {
        User.findOne({_id: req.user.id}, function(err, user) {
            if (err) {

            }
            if (user) {
                var found = false,
                    action = '';

                if (_.findWhere(user.favorites, {id: postId})) {
                    found = true;
                }

                if (found) {
                    user.favorites = _.filter(user.favorites, function(item) {
                        return item.id != postId; 
                    });
                } else {
                    user.favorites.push({id: postId});
                }

                var incrDecr = found ? -1 : 1;

                async.parallel([
                    function postUpdate(callback) {
                        Post.findOneAndUpdate({_id: postId}, {$inc: {favoriteCount: incrDecr}}, {}, function(err, post) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            if (post) {
                                callback(null, post);
                            }
                        });                     
                    },
                    function userUpdate(callback) {
                        user.save(function(err, user) {
                            if (err) {
                                callback(err);
                                return;
                            }
                            if (user) {
                                callback(null, user);
                            }
                        });
                    }
                ], function(err, results) {
                    return res.json({success: 1, action: (found ? 'remove' : 'add')});
                });
            }
        });
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kaloshin, 2014-10-28
@undassa

In order:
var postId = req.body.id; - body can be null - then the application will crash. Verification required.
if (req.user) - not quite a correct check, since then you make a request for a nested id field, which may not be there. And if it is not there, then there is no point in loading the application with an extra request to the database.
if(req.user && req.user.id) is a smarter option.
Further: everything is correct, of course, it is impossible to update 2 documents in different collections with one request. But in your case, I see no reason to use the async library. A much more ideologically correct option is to master event programming. And just call the sequence of events while executing the algorithm.

var error = function (err) {
   //
}
event.on('error', error);

// где то там в глубине кода
if(err)  return event.emit('error', err);
event.emit('user save') // в случае отсутсвия ошибок

I can comment more if needed :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question