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

问题描述 投票:0回答:1

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

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);

我创建了一个post登录请求,用于将登录用户添加到enrolledUsers数组中,问题是,我想先检查rerol.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?

node.js mongoose
1个回答
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
                }

                }
            }
        );

    });
© www.soinside.com 2019 - 2024. All rights reserved.