Home > database >  How do I create course and assign a reference to it?
How do I create course and assign a reference to it?

Time:08-27

I'm trying to assign to an exercise a user but I'm not sure if I'm doing it the right way: here is how I'm trying to do it, this is my user Model :

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

const UserSchema= new Schema({
  email: String,
  password: String,
  fullName: String,
});
module.exports = mongoose.model('User', UserSchema);

here my course mode:

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

const CoursesSchema = new Schema({
  name: String,
  type: String,
  assignedTo: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
});
module.exports = mongoose.model('Courses', CoursesSchema );

here the methode where I'm trying to create a course with a user

const createCourse = async (req, res) => {
  try {
    
     const user = await UserModel.find();
    const course= new CourseModel({
      name: req.body.name,
      type: req.body.type,

    });    
        await CourseModel.findByIdAndUpdate(
          { _id: course._id },
          { $addToSet: { assignedTo: user } },
        );  
    await course.save();
    res.json({
      success: true,
      courses: course,
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: err.message,
    });
  }
};

I'm trying to only assign the name of the user i did try {$addToSet: { assignedTo: user.fullName }} but that doesn't work I'm still learning the ref as I'm new to it, Thank you.

CodePudding user response:

You can use $addToSet only if you are trying to push new object into array.

First, you need to have user's id to whom course is assigned.

So, update your this line:

const user = await UserModel.find(); //with 
const user = await UserModel.findOne({some condition});

To save assignedTo try once with following code:

const createCourse = async (req, res) => {
  try {
    
     const user = await UserModel.findOne();
     const course= new CourseModel({
      name: req.body.name,
      type: req.body.type,
      assignedTo: user._id
    });    
    await course.save();
    res.json({
      success: true,
      courses: course,
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: err.message,
    });
  }
};
  • Related