Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

javascript - 如何在模型的对象属性中添加新对象(How to add a new Object to a property of object in a model)

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.

(我可以使用updateOne方法进行更新,但它更改了1个项目,但未更改其他项目。)

  ask by Javlon Khalimjanov translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

(当您使用此正文向URL http://localhost:3000/user/5de2cf9323f76c207c233729/course发送请求时(请注意5de2cf9323f76c207c233729是现有用户_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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...