[英]MongoDB: update a collection based on another collection
我有一個在線測驗門戶網站的項目。 這些是我的模型:
用戶模型
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 }],
});
每次向 Score 模型插入記錄后,我都想更新我的 User 模型。
不出所料,這是我的排名公式。
avg = 總分 / 總參與測驗
我如何使用 MongoDB 或 Mongoose 實現這一目標?
您可以使用貓鼬模式方法。 讓我們看看如何。
用戶架構:
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);
因此,每當您調用 save on score schema 時, post('save') 都會被觸發,您可以在此函數中更新 userSchema。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.