Mongoose在数组内的对象内的数组中添加或更新值

发布于 2025-02-09 07:15:55 字数 1299 浏览 3 评论 0原文

这是我的模式,

const courseSchema = new mongoose.Schema({
  name: String,
  code: String,
  class: String,
  credit: Number,
  overview: String,
  prerequisite: String,
  syllabus: [
    {
      moduleName: String,
      moduleDetails: String,
    },
  ],
  materials: [
    {
      moduleNo: Number,
      moduleMaterials: [String],
    },
  ],
  teacher: String,
  students: [String],
});

我想添加新材料,每次更新操作都称为我收到一个 moduleno 材料。 我想将其添加到我现有课程中的材料数组中,该课程被 courseId 过滤。因此,每次我收到 moduleno 和a 材料时,我想检查材料阵列中是否已经存在 moduleno 。如果是,则将材料添加到调节材料数组中,而不会删除调节材料中的现有URL 。如果否,然后添加一个新的对象,然后使用 moduleno 调节材料材料被推入 modulematerials 。我听说过Upsert,并认为可以使用它,但是我不确定要执行此操作的正确查询是什么。 我目前想出的是什么,即使是错误的,

  Course.updateOne(
    { _id: courseID },
    {
      $push: {
        materials: { moduleNo, moduleMaterials: { $push: { materialURL } } },
      },
    },
    { upsert: true },
    (err, result) => {
      if (err) {
        console.error(err);
      } else {
        console.log(result);
      }
    }
  );

我该如何执行此查询?

This is my schema,

const courseSchema = new mongoose.Schema({
  name: String,
  code: String,
  class: String,
  credit: Number,
  overview: String,
  prerequisite: String,
  syllabus: [
    {
      moduleName: String,
      moduleDetails: String,
    },
  ],
  materials: [
    {
      moduleNo: Number,
      moduleMaterials: [String],
    },
  ],
  teacher: String,
  students: [String],
});

I want to add new materials in which each time an update operation is called I receive a
moduleNo and a materialURL.
I want to add this to the materials array in my existing course which is filtered by courseID. So each time I receive a moduleNo and a materialURL, I want to check if moduleNo already exists in the materials array. If yes, then add materialURL into the moduleMaterials array without deleting the existing urls in moduleMaterials. If no, then add a new object with moduleNo and moduleMaterials and materialURL pushed into moduleMaterials. I've heard about upsert and think that could be used but I'm not sure what the correct queries are to do this operation.
What I've currently come up with even though it's wrong,

  Course.updateOne(
    { _id: courseID },
    {
      $push: {
        materials: { moduleNo, moduleMaterials: { $push: { materialURL } } },
      },
    },
    { upsert: true },
    (err, result) => {
      if (err) {
        console.error(err);
      } else {
        console.log(result);
      }
    }
  );

How do I do execute this query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文