I load products through endless scrolling in pieces of 12 at a time.
Sometimes I can sort them by the number of followers that they have.
The following is a description of how I track the number of followers of each product.
In a separate collection it follows that due to data caching 16mb and the number of the following values should be unlimited.
follow the pattern:
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 Following Scheme:
var ProductSchema = new mongoose.Schema({ name: { type: String, unique: true, required: true }, followers: { type: Number, default: 0 } });
Whenever a user follows / unsubscribes from 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:
1: Is there a chance that the added “follower” value inside the product may cause some kind of error that will lead to inconsistent / inconsistent data?
2: would it be better to write an aggregate for counting subscribers for each Product, or would it be too expensive / slower?
In the end, I would probably rewrite this in the DB graph as it seems more appropriate, but at the moment it is an exercise in mastering MongoDB.