【问题标题】:How to push new object nested array properties in mongoose?如何在猫鼬中推送新的对象嵌套数组属性?
【发布时间】:2020-09-03 18:17:49
【问题描述】:

这是课程架构,我想推送 内容对象,但我找不到什么好方法。请帮忙。

import mongoose from "mongoose";

export const Schema = new mongoose.Schema({
  course_en: { type: String },
  course: { type: String },
  module: [
    {
      _id: { 
        type: String
      },
      module_en: String,
      module: String,
      content: [
        {
            _id: { type: String }
          content_en: String,
          content: String,
        }
      ],
    }
  ],
});

const Course = mongoose.model("Course", Schema);

export default Course;

这是我尝试过的代码,但不起作用,它只能添加 模块对象

db.update(
      { _id: _id, "module._id": module_id },
      {
        $push: { content: data } 
      }
    )
    .then((result: any) => {
      console.log(`Content Posted ${result}`);
      response.send({ "status": "success" });
    })
    .catch((error: any) => {
      console.log(`Error ${error}`);
      response.send({ "status": "fail" });
    });

【问题讨论】:

    标签: node.js database mongodb express mongoose


    【解决方案1】:
    db.collection.update(
    { _id: _id, "module._id": module_id },
    { "$push": 
        {"module.$.content": 
            {
                "_id":"123",
                "content_en": "hello",
                "content": "hey"
            }
        }
    })
    

    【讨论】:

    • 是的,完成了我的工作。对此,我真的非常感激!感谢您的帮助!
    【解决方案2】:

    假设data 是您要添加到content 数组的对象,您可以尝试这样的操作:

    db.update(
          { _id: _id, "module._id": module_id },
          {
            $push: { "module.$.content" : data } 
          }
    )
    

    【讨论】:

      猜你喜欢
      • 2021-07-26
      • 2018-02-28
      • 2016-06-05
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      相关资源
      最近更新 更多