0
let userSchema = new Schema({
    email: {type: String, required: true},
    password: {type: String, required: true},
    name:  {type: String, required: true},
    phoneNumber: {type: Number, required: true},
    schedule: {type: String, required: true},
    courses: {type: Array, required: false}
});

I have this condition, my problem is how to add a new course to courses property but in my case course is an another object. I could update using updateOne method, but it changed 1 item but not another.

1
  • Did you try my answer? Can you please give some feedback whether it helped you or not. You ask a question, but we spend time on it, but you don't give any feedback. Commented Dec 5, 2019 at 13:07

1 Answer 1

1

As I understand, you want to embed courses into the user model.

So you need to make this change in your user model:

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

let userSchema = new Schema({
  email: { type: String, required: true },
  password: { type: String, required: true },
  name: { type: String, required: true },
  phoneNumber: { type: Number, required: true },
  schedule: { type: String, required: true },
  courses: [
    new Schema({
      name: String
    })
  ]
});

module.exports = mongoose.model("User", userSchema);

And create a course for the given user like this:

app.post("/user/:id/course", async (req, res) => {
  const result = await User.findByIdAndUpdate(
    req.params.id,
    {
      $push: {
        courses: {
          name: req.body.name
        }
      }
    },
    {
      new: true
    }
  );

  res.send(result);
});

When you send a request to url http://localhost:3000/user/5de2cf9323f76c207c233729/course with this body: (Note that 5de2cf9323f76c207c233729 is an existing user _id)

{
  "name": "Course 1"
}

The response will be like this, meaning the course is added to the user:

{
    "_id": "5de2cf9323f76c207c233729",
    "email": "[email protected]",
    "password": "123123",
    "name": "Max",
    "phoneNumber": 123123123,
    "schedule": "sc1",
    "courses": [
        {
            "_id": "5de2cfa723f76c207c23372a",
            "name": "Course 1"
        }
    ],
    "__v": 0
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.