我有一个在线测验门户网站项目。这些是我的模型:
用户模型
const userSchema = new Schema({
firstName: { type: String, required: true, maxlength: 15 },
lastName: { type: String, required: true, maxlength: 15 },
rank: Number
});
得分模型
const scoreSchema = new Schema({
userId: ObjectId,
quizId: ObjectId,
marks: Number,
answers: [{ type: Object }],
});
我想在将记录插入分数模型后每次更新用户模型。
毫不奇怪,这是我的排名公式。
avg =总分数/总参与测验
如何使用MongoDB或Mongoose来实现这一目标?
答案 0 :(得分:0)
您可以使用猫鼬schema method。让我们看看。
用户架构:
const userSchema = new Schema({
firstName: { type: String, required: true, maxlength: 15 },
lastName: { type: String, required: true, maxlength: 15 },
rank: Number
});
const User = mongoose.model('User', userSchema);
得分模式:
const scoreSchema = new Schema({
userId: ObjectId,
quizId: ObjectId,
marks: Number,
answers: [{ type: Object }],
});
// Add post save method on this schema
scoreSchema.post('save', function (doc) {
console.log('this fired after a document was saved');
// doc.userId is you user for this score so
// rank:calculated_rank you formula here
User.updateOne({_id:doc.userId} , {rank:calculated_rank})
});
// model
const Score = mongoose.model('Score', scoreSchema);
因此,每当您在得分架构上调用保存时,就会触发post('save'),并且您可以在此函数中更新userSchema。