【发布时间】:2017-04-19 00:06:38
【问题描述】:
我正在通过无限滚动加载产品,一次 12 个块。
有时,我可能想按他们有多少关注者来排序。
以下是我如何跟踪每个产品有多少关注者。
由于 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
}
});
每当用户关注/取消关注产品时,我都会运行此功能:
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 个文档,这不是整体原子的。这可能是任何一个步骤都失败了。例如,跟随成功但增量失败。阅读:Two phased commits.
标签: javascript node.js mongodb mongoose