如何更新MongoDB NodeJS数组中的特定对象

时间:2020-08-29 16:14:14

标签: javascript node.js reactjs mongodb mongoose

我正在创建保留系统,现在我需要更新数组中的特定对象。

{
   "_id":{
      "$oid":"5f3fdcf463153719845e32e9"
   },
   "do_kogo":"Doctor",
   "Startdate":"8/21/2020, 1:00:00 AM",
   "EndDate":"8/21/2020, 2:00:00 AM",
   "StartdateFormatPL":"21.08.2020, 01:00:00",
   "EndDateFormatPL":"21.08.2020, 02:00:00",
   "godziny":[
      {
         "id":"rbprEs",
         "hour":"21.08.2020, 01:00:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"lT8WkM",
         "hour":"21.08.2020, 01:05:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"n4PJ3V",
         "hour":"21.08.2020, 01:10:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"aHM-Gn",
         "hour":"21.08.2020, 01:15:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"-EFbRV",
         "hour":"21.08.2020, 01:20:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"X64wkx",
         "hour":"21.08.2020, 01:25:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"eXv451",
         "hour":"21.08.2020, 01:30:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"xxni5q",
         "hour":"21.08.2020, 01:35:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"sTkns7",
         "hour":"21.08.2020, 01:40:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"MaffJR",
         "hour":"21.08.2020, 01:45:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"8DFBra",
         "hour":"21.08.2020, 01:50:00",
         "isBooked":false,
         "isConfirmed":false
      },
      {
         "id":"3Jb5yE",
         "hour":"21.08.2020, 01:55:00",
         "isBooked":false,
         "isConfirmed":false
      }
   ],
   "__v":{
      "$numberInt":"0"
   }
}

我需要的是通过其id:5f3fdcf463153719845e32e9查找主对象,然后通过其ID(例如“ rbprEs”)从godziny[]查找主对象。之后,我需要将isBooked的值从false更改为True或其他方式。

我需要获得:

{
             "id":"rbprEs",
             "hour":"21.08.2020, 01:00:00",
             "isBooked":true,
             "isConfirmed":false
          },

我正在尝试下面的代码,但无法正常工作。

    router
.post("/upgrade/:id/:id2", (req, res) => {
  ReservationHours.findOneAndUpdate(
    { 
      // convert id to object id if not using (mongoose.Types.ObjectId(req.params.id))
      _id: req.params.id, 
      godziny: {
          $elemMatch: {
              id: req.params.id2,
              isBooked: false
          }
      }
    },
    // use positional operator $ to update in specific object
    { $set: { "godziny.$.isBooked": true } }
  )
  .then(ReservationHours =>
      ReservationHours.save().then(() => res.json({ success: true }))
  )
  .catch(err => res.status(404).json({ success: false }));
});

但是如何获取和更新如此嵌套的参数?

该帖子的React中的代码:

export const updateReservationHours = (id, id2) => (dispatch, getState) => {
    axios.post(`/reservationshours/${id}/${id2}`, tokenConfig(getState)).then(res =>
      dispatch({
        type: UPDATE_RESERVATION_HOURS,
        payload: (id, id2)
      })
    )
    .catch(err =>
      dispatch(returnErrors(err.response.data, err.response.status))
    );
  };

1 个答案:

答案 0 :(得分:1)

您可以尝试findOneAndUpdate

ReservationHours.findOneAndUpdate(
  { 
    // convert id to object id if not using (mongoose.Types.ObjectId(req.params.id))
    _id: req.params.id, 
    godziny: {
        $elemMatch: {
            // you can set it dynamic by using (req.params.godziny)
            // if its multiple and array then use id: { $in: req.params.godziny }
            id: "rbprEs", 
            isBooked: false
        }
    }
  },
  // use positional operator $ to update in specific object
  { $set: { "godziny.$.isBooked": true } },
  // get updated original document
  { projection: { "godziny.$": 1 } } 
)
.then(ReservationHours =>
    ReservationHours.save().then(() => res.json({ success: true }))
)
.catch(err => res.status(404).json({ success: false }));