【问题标题】:How can i add, update, delete nested objects in mongoDB如何在 mongoDB 中添加、更新、删除嵌套对象
【发布时间】:2021-07-19 18:01:22
【问题描述】:

我是 mongoDB 和后端的新手。我有一个嵌套的 MongoDB 模型模式。我需要更新、删除和添加该嵌套对象/数组。我该怎么做?

如何从列数组和恢复数组中删除/添加/更新项目。

const userSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
    },
    password: {
        type: String,
    },
    columns: [
        {
            title: {
                type: String,
                required: true,
            },
            resumes: [
                {
                    name: {
                        type: String,
                        required: true,
                    },
                    resume: {
                        type: String,
                        required: true,
                    },
                },
            ],
        },
    ],
});

const Users = mongoose.model('Users', userSchema);

这是我的架构

【问题讨论】:

  • 只需访问变量,如果它们在一个数组中,然后循环访问它并使用条件访问您想要的变量。

标签: node.js mongodb mongoose


【解决方案1】:

将新项目添加到列数组中:

let newData = {title: "New Title", resumes: []}    
let userData = await User.findByIdAndUpdate(userID, {
  $push: {
    columns: newData,
  },
});

将新项目添加到列内的简历数组中:

let newData = {name: "New Name", resume: "New Resume"}
let userData = await User.updateOne(
  {
    _id: mongoose.Types.ObjectId("60f54774761788cd80f56xxx"),
    "columns._id": mongoose.Types.ObjectId("60f54774761788cd80f56xxx"),
  },
  {
    $push: { "columns.$.resumes": newData },
  }
);

同样,您可以使用$pull 运算符从数组中删除一个对象,并使用$(update) 更新数组中的元素

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 2021-01-23
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多