Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (19.9k points)

I have a mongoose schema that looks like :-

    "_id" : ObjectId("some_id"), 

    "repDet" : {

        "devIDs" : [

            "dev1_B37", 

            "dev2_B38", 

            "dev3_B26"

        ], 

        "sensors" : [

            "D30"

        ], 

        "triggers" : [

            "initial"

        ]

}

I want to pull "dev2_B38" from the array "devIDs" inside the object "repDet". The following command works in mongo db :-

schedules.updateOne({ added_by: currentUser, "repDet.devIDs": "dev2_B38" },{$pull : {"repDet.devIDs": "dev2_B38"}})

perfectly.

But the same command doesnt work in mongoose. The mongoose version that I have tried on is 5.0.18 & 5.7.11. what it does it removes all the other devIDs from the array and keeps just the "dev_B38" and also converting "devIDs" into a string from an array. The output looks like :-

    "_id" : ObjectId("some_id"), 

    "repDet" : {

        "devIDs" : "dev2_B38",

        "sensors" : [

            "D30"

        ], 

        "triggers" : [

            "initial"

        ]

}

I have tried updateOne, update, findOneAndUpdate all of these. I also tried modifying it like :-

schedules.updateOne({ added_by: currentUser, "repDet.devIDs": "dev2_B38" },{$pull : {"repDet" {"devIDs": "dev2_B38"}}}) 

but still it gave me the same result.

The exact schema is :-

var scheduleSchema = new mongoose.Schema({

    title: { type: String },

    message: { type: String },

    devID: { type: String },

    sensors: [{

      sensorId: String,

      sensorName: String,

      unit: String

    }],

    selectedContacts: [{

      _id: { type: mongoose.Schema.Types.ObjectId, ref: 'Contact' },

      name: String,

      mobiles: [Number],

      emails: [String]

    }],

    repDet: { type: Object },

    invocationTime: { type: String },

    invocationDays: Array,

    startTime: { type: String },

    endTime: { type: String },

    interval: { type: Number },

    repeat: { type: Number },

    url: String

  });

Kindly help me with this. Thank you

1 Answer

0 votes
by (25.1k points)

You need to use the updateOne method on schedules object with _id being passed as current user, like this:

schedules.updateOne({ _id: currentUser},

 {$pull : {"repDet.devIDs":"dev1_B37"}}) 

Browse Categories

...