我喜欢在mongodb集合中为有他所观看课程的用户创建一条记录。如果他已完成课程,则应在completed_courses字段中进行更新。对于此操作,我要执行以下操作以使数据库达到三次。
有人可以建议其他方法来简化操作,以便我一次或两次访问数据库。
模型
const userCourseListSchema = new Schema({
course_id: {
type: Number,
required: true
},
completed:{
type:Boolean
}
});
const userCourseStatusSchema = new Schema({
user_id: {
type: Number,
unique: true,
required: [true, 'Invalid User ID']
},
completed_courses:{
type:Number
},
courselist:{
type: [userCourseListSchema]
}
});
输入
{
"course_id":1,
"completed":true
}
预期产量
{
"user_id":1,
"completed_courses":1,
"courselist":[
{
"course_id":1,
"completed":true
}
]
}
工作方法
async updateCourse(){
let newUserCourseData ={
user_id:1,
completed_courses:0,
courselist:{
"course_id":1,
"completed":true
}
};
await UserCourseStatusModel.create(newUserCourseData);
let watchCount = await this.totalWatchCount(1);
let result = await UserCourseStatusModel.findOneAndUpdate({user_id:1}, {$set:{completed_courses:watchCount} }, {new: true, upsert:true}).exec();
return {result};
}
async totalWatchCount(userId){
let watchCourses = await UserCourseStatusModel.aggregate([
{
$match:{
user_id:userId
}
}
]).exec();
let watcher = watchCourses[0].courselist;
let watchCourseCount = 0;
for (let val in watcher){
if(watcher[val].completed===true){
watchCourseCount++;
}
}
return watchCourseCount;
}