Mongoose data flow
我建立了一个简单的MERN应用程序,用户可以在其中对电话号码进行评分。用户只需填写电话号码,然后选择评分(1-5星级),他们的城市
我认为您的方法总是会遇到异步问题。我不相信您可以"同步"这些钩子;似乎有悖于MongoDB的一切。但是,在较高的级别上,您可能会在运行时获取总计/摘要方面取得更大的成功,而不是尝试始终保持它们同步。例如,如果您需要给定移动设备的消息总数,为什么不这样做:
1 | Messages.find({mobile: mobile._id}) |
然后计算结果?这样可以节省您存储摘要并保持更新的时间。但是,我也认为您当前的方法可行,但是您可能需要废弃" countDocuments "。更异步友好的东西,例如:
1 2 3 4 | Mobile.aggregation([ { $match: { _id: mobile._id } }, { $add: ["$mobile.messagesCount", 1 ] } ]); |
我最终认为,如果将Messages作为数组存储在Mobile中,则您的设计将会得到加强,因此您可以将消息推送到其中。但是要直接回答这个问题,聚合应该使所有内容保持整洁。
首先,我们需要在此处修复某些数据库结构
移动架构
1 2 3 4 5 6 7 8 9 10 11 | const mobileSchema = new Schema({ number: { type: String, required: true }, plan: { type: String, required: true }, date: { type: Date, default: Date.now, required: true, index: 1 }, //messagesCount: { type: Number, default: 0, index: 1 }, //lastMessageDate: { type: Date, index: 1 }, // normal mean //globalRating: { type: Number, default: 0, index: 1 }, // weighted mean //averageRating: { type: Number, default: 0, index: 1 } }); |
消息架构
1 2 3 4 5 6 7 8 | const messageSchema = new Schema({ comment: { type: String, required: true }, city: { type: Schema.Types.ObjectId, ref: 'City', required: true, index: 1 }, //rating: { type: Number, required: true, index: 1 }, date: { type: Date, default: Date.now, required: true, index: 1 }, mobile: { type: Schema.Types.ObjectId, ref: 'Mobile', required: true }, user: { type: Schema.Types.ObjectId, ref: 'User', required: true } }); |
评分系统(接受所有评分或将其设为一组)
(分子
我找到了这个答案:在MongoDB中锁定文档
我将计算后挂接中所需的所有值(messagesCount,globalRating等),然后在最终findOneAndUpdate操作期间检查移动文档是否具有相同的__v(版本)值(因为此操作将文档锁定并可以增加__v)。如果它具有不同的__v,那么我将再次调用post钩子,以确保它将计算正确的值。