在嵌入式文档节点猫鼬中找到一个id

时间:2019-01-12 09:38:40

标签: node.js mongoose

我有一个具有以下结构的课程模型:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const user_shortid = require('shortid');

// Create Course schema

const CourseSchema = new Schema({

    courseDetail: {
        type: String
    },
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    enrolledUsers: [{
        type: Schema.Types.ObjectId,
        ref: 'users'
    }],
    currentStatus: {
        type: String,
        default: 'Planned'
    }

});

mongoose.model('courses', CourseSchema);

我创建了一个发布请求,用于将登录用户添加到enrolledUsers数组中,问题是,我想先检查req.user.id是否存在于enrolledUsers数组中。以下是我的发帖请求:

router.post('/joincourse', [ensureAuthenticated], (req, res) => {

    Course.findByIdAndUpdate({ _id: req.body.coursecode },
        { $push: { enrolledUsers: req.user.id } },
        { safe: true, upsert: true },
        function (err, doc) {
            if (err) {
                req.flash('error_msg', 'Could not enroll in the course');
                res.redirect('/dashboard');
            } else {
                req.flash('success_msg', 'You are now enrolled in the course');
                res.redirect('/dashboard');
            }
        }
    );

});

现在的行为是用户可以在同一课程中一次又一次地注册。

是否有某种方法可以在添加之前检查enrolledUsers数组中的req.user.id?

1 个答案:

答案 0 :(得分:0)

您可以先使用find()查找用户,然后如果存在用户,请对其进行更新,否则 给出这样的错误

    router.post('/joincourse', [ensureAuthenticated], (req, res) => {

        Course.findById({ _id: req.body.coursecode },
            function (err, doc) {
                if (err) {
                    req.flash('error_msg', 'Could not enroll in the course');
                    res.redirect('/dashboard');
                } else {
                 if(doc){
                     if(!doc.enrolledUsers.includes(req.user.id)){ // here is the checking 

                         doc.enrolledUsers.push(req.user.id);
                         doc.save();
                         req.flash('success_msg', 'You are now enrolled in the course');
                         res.redirect('/dashboard');
                     }
                }else{ 
                    // show error msg
                }

                }
            }
        );

    });
相关问题