简体   繁体   中英

How to push a value to an array field only if it meets a condition in mongoDB?(Nodejs)

I apologize for my poor way of explaining my issue. I am trying to update my schema's notes and assignmentHistory fields. I have no issues updating notes field but with the assignmentHistory field what I am trying to do is append values to the array only if the assingedTo value has changed from it's last value or is not empty only then $push to assignmentHistory array, otherwise don't add anything to assigmentHistory array. Basically, how do I prevent $push not add anything to the assignmentHistory array, not even empty object with _id field? Below is snippet of my code

const RequestSchema = new Schema(
  {
title: { type: String, required: true, max: 32, min: 6 },
priority: { type: String, emum: ["low", "medium", "high"] },
notes: [
      {
        commentNotes: {
          comment: { type: String, max: 200 },
          commentBy: { type: Schema.Types.ObjectId, ref: "User" },
          commentDate: { type: Date },
       }
]
assignedTo: { type: Schema.Types.ObjectId, ref: "User" },
assigmentHistory: [
      {
        techName: { type: Schema.Types.ObjectId, ref: "User" },
        assignedDate: { type: Date },
      }
    ]
}

let noteObj={};
let techobj={};

await RequestModel.findOneAndUpdate(
      { _id },

      {
        $push: {
          notes: [noteObj],
          assignmentHistory:[techobj]
        },
      },
      { new: true }
    );

In order to only push an element in an array if the value is not present yet, you can use $addToSet . See this example on mongoplayground . Regarding handling the empty object - I'd just do it on the client side and dynamically build the query. So something like:

const addToSetObj = {};
if(!isEmpty(noteObj)) { // use one of the method for isEmpty described here https://stackoverflow.com/q/679915/3761628
  pushObj.notes = noteObj;
}
if(!isEmpty(techObj)) {
  pushObj.assignmentHistory = techObj;
}
await RequestModel.findOneAndUpdate(
      { _id },
      {
        $addToSet: addToSetObj
      },
      { new: true }
    );

I do have a work around but would like a more professional way to avoid adding empty objects to the array field.

if (
  assignedTo &&
  assignedTo.toString() !== oldRequest.assignedTo.toString()
) {
      await RequestModel.findOneAndUpdate(
        { _id },

        {
          $set: requestFields,
          $push: {
            notes: [noteObj],
          },
          $addToSet: { assigmentHistory: [newtech_info_object] },
        },
        { new: true }
      );
    } else {
      await RequestModel.findOneAndUpdate(
        { _id },

        {
          $set: requestFields,
          $push: {
            notes: [noteObj],
          },
        },
        { new: true }
      );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM