Shashank Padwal
Shashank Padwal

Reputation: 323

how to use one field value to update another one in mongoose?

I have following document:

{
    "logout_time": null,
    "duration": null,
    "_id": "5e8e8dd2b0c2a30ad12973f9",
    "user_id": "5e8109ea5bc5822aa531a57d",
    "comp_id": "5e8d16a0c1834fd3d8e9e1eb",
    "org_id": "5e8c7a34c358958a58be4755",
    "login_time": "2020-03-16T05:29:34.000Z",
    "server_time": "2020-04-09T02:52:02.646Z",
    "__v": 0
}

I am using mongoose and nodeJS. now when I get logout time I update it in document using following function:

async function logOut(user_id, comp_id, time) {
  try {
    let updateObj = await Session.updateMany(
      { user_id: user_id, comp_id: comp_id, logout_time: null },
      {
        $set: {
          logout_time: time,
        },
      }
    );
    return {
      status: "success",
      msg: "Logged Out successfully",
      update_info: updateObj,
    };
  } catch (err) {
    return { status: "failed", message: err.message };
  }
}

but now I want to update duration as logout time - login time when I get logout time, I tried many things but can't get it done using mongoose. I am new to mongo and had used MySQL.

I Tried following but its not working:

async function logOut(user_id, comp_id, time) {
  try {
    let updateObj = await Session.updateMany(
      { user_id: user_id, comp_id: comp_id, logout_time: null },
      {
        $set: {
          logout_time: time,
          duration: { $subtract: [Date(time), "$login_time"] },
        },
      }
    );
    return {
      status: "success",
      msg: "Logged Out successfully",
      update_info: updateObj,
    };
  } catch (err) {
    return { status: "failed", message: err.message };
  }
}

so my question is how can we update a field in mongoDB using other field's value?

Upvotes: 1

Views: 2551

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

Because $subtract is an aggregation pipeline operators so you need to use it in aggregation. Fortunately, starting in MongoDB 4.2, you can use the aggregation pipeline for update operations. Since you're using mongoDB version 4.2.2 so the below should work:

Session.updateMany(
  { user_id: user_id, comp_id: comp_id, logout_time: null },
  [{
    $set: {
      logout_time: new Date(time),
      duration: { $subtract: [new Date(time), "$login_time"] },
    },
  }]
)

See: Updates with Aggregation Pipeline

Upvotes: 4

Related Questions