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

时间:2019-04-08 14:24:49

标签: javascript mongodb mongoose mongodb-query

型号:

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)
  }
}

调试器:

  

猫鼬:users.createIndex({电子邮件:1},{唯一:真实,背景:   true}){sub:'5cab48ebec24577ab3329fcd',iat:1554729210}

     

猫鼬:users.findOne({_id:ObjectId(“ 5cab48ebec24577ab3329fcd”)},   {投影:{}})

     

猫鼬:projects.findAndModify({'seats._id':   ObjectId(“ 5cab529bcafa027e30ee229c”)},[],{'$ setOnInsert':{   createdAt:new Date(“ Mon,08 Apr 2019 14:45:56 GMT”)},'$ set':{   'seats。$。employee':'email@email.com',更新时间:新   Date(“ Mon,08 Apr 2019 14:45:56 GMT”)}},{new:true,upsert:false,   移除:false,投影:{}})(节点:33302)DeprecationWarning:   不推荐使用collection.findAndModify。使用findOneAndUpdate,   而是使用findOneAndReplace或findOneAndDelete。

     

项目为空

我想通过seatsid中搜索特定对象。 这个特定的座位应该更新。就我而言,我想更新employee字段。

如果我执行findOne({"seats._id": req.params.id}),我将退回项目,但是findOneAndUpdate返回null

1 个答案:

答案 0 :(得分:2)

您需要$ positional operator,因为seats是一个数组,如果只想更新一个字段,则应该使用$set运算符

const project = await Project.findOneAndUpdate({
  "seats._id": req.params.id
}, {
  $set: { "seats.$.employee": req.body.employee }
}