通过ID更新对象中的MongoDB对象

模型:


const projectSchema = new Schema({

  name: {

    type: String,

    maxlength: 50

  },

  description: {

    type: String

  },

  projectLead: {

    type: String

  },

  start: {

    type: String

  },

  end: {

    type: String

  },

  projectType: {

    type: String

  },

  claimId: {

    type: String

  },

  organization: {

    type: String

  },

  seats: [{

    id: String,

    employee: String,

    role: String,

    start: String,

    end: String,

    workload: Number,

    skills: Array,

    approved: Boolean

  }]

}, {

  timestamps: true

})

模型响应示例:


{

    "project": {

        "_id": "5cab4b9bc9b29a7ba2363875",

        "name": "Project Title",

        "description": "Project description",

        "projectLead": "email@email",

        "start": "2018-06-01T09:45:00.000Z",

        "end": "2019-06-31T09:45:00.000Z",

        "claimId": "AIIIIII",

        "organization": "Company ACE",

        "seats": [

            {

                "skills": [

                    "Node.js",

                    "Vue.js"

                ],

                "_id": "5cab548e5cefe27ef82ca313",

                "start": "2018-06-01T09:45:00.000Z",

                "end": "2019-06-31T09:45:00.000Z",

                "role": "Developer",

                "approved": false,

                "workload": 20,

                "employee": ''

            }

        ],

        "createdAt": "2019-04-08T13:24:43.253Z",

        "updatedAt": "2019-04-08T14:02:54.257Z",

        "__v": 0

    }

}

控制器:


exports.updateSeatEmployee = async (req, res, next) => {

  try {

    const project = await Project.findOneAndUpdate({

      "seats._id": req.params.id

    }, {

      "seats.employee": req.body.employee

    }, {

      new: true

    })

    console.log("project", project);

    return res.json({

      project: project

    })

  } catch (error) {

    next(error)

  }

}


我要搜索特定的对象seats由它id。这个特定的座位应该更新。就我而言,我想更新该employee字段。


如果我这样做,findOne({"seats._id": req.params.id})我会把项目拿回来,但会findOneAndUpdate返回null。


Smart猫小萌
浏览 289回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript