首页 > 解决方案 > 如何在 mongoDB 中添加、更新、删除嵌套对象

问题描述

我是 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.jsmongodbmongoose

解决方案


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

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

要将新项目添加到列内的 resumes 数组中:

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)更新数组中的元素


推荐阅读