[英]MongoDB: update a collection based on another collection
I've a project of online quiz portal web site.我有一个在线测验门户网站的项目。 These are my models:这些是我的模型:
User model用户模型
const userSchema = new Schema({
firstName: { type: String, required: true, maxlength: 15 },
lastName: { type: String, required: true, maxlength: 15 },
rank: Number
});
Score model评分模型
const scoreSchema = new Schema({
userId: ObjectId,
quizId: ObjectId,
marks: Number,
answers: [{ type: Object }],
});
I want to update my User model every time after I insert a record to the Score model.每次向 Score 模型插入记录后,我都想更新我的 User 模型。
This is unsurprisingly my formula for the rank.不出所料,这是我的排名公式。
avg = Total marks / Total participated quizzes avg = 总分 / 总参与测验
How could I achieve this using MongoDB or Mongoose?我如何使用 MongoDB 或 Mongoose 实现这一目标?
You can utilize the mongoose schema method .您可以使用猫鼬模式方法。 let see how.让我们看看如何。
User Schema:用户架构:
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);
Score Schema:分数架构:
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);
So whenever you call save on score schema then post('save') will be fired and you can update userSchema in this function.因此,每当您调用 save on score schema 时, post('save') 都会被触发,您可以在此函数中更新 userSchema。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.