我「通過在同一時間在12塊的無限滾動M狀加載產品。
有時,我會想他們有多少追隨者整理這些。
下面的是我如何跟蹤。有多少追隨者每個產品都有
接踵而來的是在一個單獨的集合,因爲16MB數據帽和量如下應該是無限
如下模式:
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
}
});
產品所遵循的模式:
var ProductSchema = new mongoose.Schema({
name: {
type: String,
unique: true,
required: true
},
followers: {
type: Number,
default: 0
}
});
只要用戶遵循/ unfollows一個產品,我運行這個功能:
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);
})
};
我對這個問題:
1 :產品中遞增的「跟隨者」值是否有可能遇到某種錯誤,導致不匹配/不匹配持續的數據?
2:倒不如寫一個彙總數對每個產品的追隨者,還是那樣過於昂貴/慢?
最終,我可能會在graphDB改寫這個,因爲它似乎更適合,但現在 - 這是在掌握MongoDB的練習。
關於#1:單個文檔更新是原子性的,但是您要更新2個集合中的2個文檔,這不是全部原子集合。這可能是任何一個步驟都失敗了。例如,跟隨是成功的,但增量失敗。閱讀:[兩階段提交。](https://docs.mongodb.com/v3.2/tutorial/perform-two-phase-commits) –