javascript - 将对象推送到数组,该数组是数组 Mongoose 中对象的字段

标签 javascript node.js mongodb mongoose

基本上我有以下架构。

{
    ...,
    description: {
        type: String,
        required: true,
        trim: true
    },
    tags: {
        type: [{
            type: String
        }]
    },
    lessons: [{
            name: String,
            description: String,
            video_path: String,
            comments: [
                {
                    user: mongoose.Schema.ObjectId,
                    content: String,
                    createdAt: {
                        type: Date, 
                        default: Date.now
                    }
                }
            ]
        }]
    ,
    createdAt: {
        type: Date
    }
}

当给定类(class)对象的 id 时,我想将以下对象插入到 lesson 对象的 comments 数组中。

{
  userId: "5e1b4790f7a3ca42accfeed3",
  content: "First comment"
}

以下是我尝试过的。但是,它不会引发任何错误,但它也不会向数据库插入任何注释。感谢您提供任何有用的建议。

addComment: async (courseId, lessonId, userId, content, callback) => {
    Course.update(
      { _id: courseId, "lessons._id": lessonId },
      {
        $push: {
          comments: {
            user: userId,
            content: content
          }
        }
      },
      function(err, data) {
        if (err) {
          console.log(err);
          return callback(err, null);
        } else {
          console.log(data);
          return callback(null, data);
        }
      }
    );
  }

编辑:

收集数据:

{ 
"_id" : ObjectId("5e1b4790f7a3ca42accfeed3"), 
"tags" : [ "mathematics", "beginner", "fundamentals" ], 
"name" : "Mathematics Toobox", 
"description" : "Mathematics includes the study of such topics as quantity (number theory), structure (algebra), space (geometry), and change (mathematical analysis).", 
"price" : 1500, 
"lessons" : [ 
    { 
      "_id" : ObjectId("5e1b48d9f7a3ca42accfeed4"), 
      "name" : "Welcome to the course", 
      "description" : "Welcome to Mathematics Toolbox course\n I’ll be your instructor for this course that runs for xx weeks ending on XXXXX.\n1. Access the technology tutorial located on your My Home page if you are new to the learning Hub, this online learning management system.", 
      "video_path" : "uploads\\1578846427336-Shakira - Hips Don't Lie ft. Wyclef Jean.mp4" 
    }, 
    { 
      "_id" : ObjectId("5e1e8f80cf166a2cb82b7a5e"), 
      "name" : "Number system", 
      "description" : "Baby just love me love me love me\nBaby just hold me hold me hold me\nOh love me ",
      "video_path" : "uploads\\1579061121969-Ellis - Migraine (feat. Anna Yvette) [NCS Release].mp4" 
    } 
], 
  "createdAt" : ISODate("2020-01-12T16:21:36.778Z"), 
  "__v" : 0, 
  "cover_path" : "uploads\\1578846099107-img_4.jpg" 
}

最佳答案

您的架构中存在一些问题。

我认为你想要一个字符串标签数组。

您还需要使用 ref 属性来引用 User 模型。

因此架构必须像这样更新: (我假设您在模型创建中使用了User。)

const mongoose = require("mongoose");

const courseSchema = new mongoose.Schema({
  description: {
    type: String,
    required: true,
    trim: true
  },
  tags: {
    type: [String]
  },
  lessons: [
    {
      name: String,
      description: String,
      video_path: String,
      comments: [
        {
          user: {
            type: mongoose.Schema.ObjectId,
            ref: "User"
          },
          content: String,
          createdAt: {
            type: Date,
            default: Date.now
          }
        }
      ]
    }
  ],
  createdAt: {
    type: Date
  }
});

module.exports = mongoose.model("Course", courseSchema);

现在您可以使用 findByIdAndUpdate 方法进行推送和 filtered positional operator $ 。 添加这样的评论:

  Course.findByIdAndUpdate(
    { _id: courseId },
    {
      $push: { "lessons.$[lesson].comments": { user: userId, content } }
    },
    {
      arrayFilters: [{ "lesson._id": lessonId }],
      new: true
    },
    function(err, data) {
      if (err) {
        console.log(err);
         return callback(err, null);
      } else {
        console.log(data);
        return callback(null, data);
      }
    }
  );

测试:

假设您有一个_id:5e20954dc6e29d1b182761c9的用户,以及这样的类(class):

{
    "tags": [
        "tag1",
        "tag2"
    ],
    "_id": "5e209631a90e651e9c238df2",
    "description": "description1",
    "lessons": [
        {
            "comments": [],
            "_id": "5e209631a90e651e9c238df3",
            "name": "lesson1 name",
            "description": "lesson1 description",
            "video_path": "lesson1 video_path"
        }
    ],
}

当您发送包含这些值的评论时:

    courseId = "5e209631a90e651e9c238df2",
    lessonId = "5e209631a90e651e9c238df3",
    userId = "5e20954dc6e29d1b182761c9",
    content = "Comment Content"

结果将是:

{
    "_id" : ObjectId("5e209631a90e651e9c238df2"),
    "tags" : [
        "tag1",
        "tag2"
    ],
    "description" : "description1",
    "lessons" : [
        {
            "comments" : [
                {
                    "_id" : ObjectId("5e2099799edf132a08c2b997"),
                    "user" : ObjectId("5e20954dc6e29d1b182761c9"),
                    "content" : "Comment Content",
                    "createdAt" : ISODate("2020-01-16T20:12:25.243+03:00")
                }
            ],
            "_id" : ObjectId("5e209631a90e651e9c238df3"),
            "name" : "lesson1 name",
            "description" : "lesson1 description",
            "video_path" : "lesson1 video_path"
        }
    ]
}

关于javascript - 将对象推送到数组,该数组是数组 Mongoose 中对象的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773833/

相关文章:

javascript - Html5 Canvas : alternative for drawImage()

javascript - 来自 Promise React Native 的结果

javascript - 我必须发出第二个 GET 请求才能获得我想要的响应

尝试更改显示属性时,javascript 函数不生效

node.js - 将 'virtual' 变量添加到 Mongoose 模式?

javascript - 将环境变量从 package.json 传递到 React 应用程序

MongoDB 查询在集合中找不到文档

ruby-on-rails - 如何在 mongoid/rails 中获取一个字段?

java - 无法覆盖 onBeforeConvert : "...have the same erasure, yet neither overrides the other"

javascript - 使用 google-passport-oauth 登录后 req.user 未定义