0

In my situation I just need my result but without my objectID in my array.

This is my method :

return Room.findOne(
    {
      _id: idRoom,
      participants: {$elemMatch: {$ne: this.currentUser.profile}},
    },
    {
      'participants.$': 1,
    }
  )

With elementMatch, the problem is when you found the object, only the first object is returned.

This is my result :

"result": {
    "_id": "5da5e77f51e08708b79565e8",
    "participants": [
       "5da4d5b40cc94f04a7aaad40"
    ],

And this is the real result I need

"result": {
    "_id": "5da5e77f51e08708b79565e8",
    "participants": [
       "5da4d5b40cc94f04a7aaad40"
       "fwnert9248yrhnqwid13982r" // I have another participants
    ],

And my model is just like this :

const RoomSchema = new Schema({
  participants: [{type: Schema.Types.ObjectId,ref: 'Profile'}],
  ...
}, options)

For others reasons, I can't use aggregate, thank you if you have the solution

1 Answers1

1

So I think you are trying to shape a resultset in mongo with the findOne() method, and any use of the aggregation pipeline framework is out of the question and unavailable for other reasons.

I am not sure this is possible. I believe you will need to perform multiple steps to achieve your desired results. If you can use aggregation pipeline framework here is a pipeline to suit the desired results (I believe)...

db.Room.aggregate(
    [
        {
            "$match": { _id: ObjectId(idRoom)}
        },
        {
            $project: {
                "participants": {
                    $filter: {
                        input: "$participants",
                        as: "participant",
                        cond: {$ne: ["$$participant", this.currentUser.profile] }
                    }
                }
            }
        }
    ]
)

...but if you cannot use aggregation pipeline then here is a mongoshell script that accomplishes the task in several steps. The strategy is to capture the whole document by _id then remove the data element from the array then echo the results...

var document = db.Room.findOne( { _id: ObjectId("5da64a62cd63abf99d11f210") } );
document.participants.splice(document.participants.indexOf("5da4d5b40cc94f04a7aaad40"), 1);
document;
barrypicker
  • 9,740
  • 11
  • 65
  • 79