2
\$\begingroup\$

I'm loading products via an infinite scroll in chunks of 12 at a time.

At times, I may want to sort these by how many followers they have.

Below is how I'm tracking how many followers each product has.


Follows are in a separate collection, because of the 16mb data cap, and the amount of follows should be unlimited.

follow schema:

var FollowSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.ObjectId,
        ref: 'User'
    },
    product: {
        type: mongoose.Schema.ObjectId,
        ref: 'Product'
    },
    timestamp: {
        type: Date,
        default: Date.now
    }
});

Product that is followed schema:

var ProductSchema = new mongoose.Schema({
    name: {
        type: String,
        unique: true,
        required: true
    },
    followers: {
        type: Number,
        default: 0
    }
});

Whenever a user follows / unfollows a product, I run this function:

ProductSchema.statics.updateFollowers = function (productId, val) {
    return Product
        .findOneAndUpdateAsync({
            _id: productId
        }, {
            $inc: {
                'followers': val
            }
        }, {
            upsert: true,
            'new': true
        })
        .then(function (updatedProduct) {
            return updatedProduct;
        })
        .catch(function (err) {
            console.log('Product follower update err : ', err);
        })
};

My questions about this:

  1. Is there a chance that the incremented "follower" value within product could hit some sort of error, resulting in un matching / inconsistent data?

  2. Would it be better to write an aggregate to count followers for each Product, or would that be too expensive / slow?

Eventually, I'll probably rewrite this in a graphDB, as it seems better suited, but for now — this is an exercise in mastering MongoDB.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.