Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose pull ObjectId from array

i'm trying to do a pretty simple operation, pull an item from an array with Mongoose on a Mongo database like so:

User.update({ _id: fromUserId }, { $pull: { linkedUsers: [idToDelete] } });

fromUserId & idToDelete are both Objects Ids.

The schema for Users goes like this:

var UserSchema = new Schema({
  groups: [],
  linkedUsers: [],
  name: { type: String, required: true, index: { unique: true } }
});

linkedUsers is an array that only receives Ids of other users.

I've tried this as well:

User.findOne({ _id: fromUserId }, function(err, user) {
  user.linkedUsers.pull(idToDelete);
  user.save();
});

But with no luck.

The second option seem to almost work when i console the lenghts of the array at different positions but after calling save and checking, the length is still at 36:

 User.findOne({ _id: fromUserId }, function(err, user) {
    console.log(user.linkedUsers.length); // returns 36
    user.linkedUsers.pull(idToDelete);
    console.log(user.linkedUsers.length); // returns 35
    user.save();
  });

So it looks like i'm close but still, no luck. Both Ids are sent via the frontend side of the app. I'm running those versions:

"mongodb": "^2.2.29",
"mongoose": "^5.0.7",

Thanks in advance.

like image 765
kevin Avatar asked Feb 26 '18 11:02

kevin


2 Answers

You need to explicitly define the types in your schema definition i.e.

groups: [{ type: Schema.Types.ObjectId, ref: 'Group' }], 
linkedUsers: [{ type: Schema.Types.ObjectId, ref: 'User' }]

and then use either

User.findOneAndUpdate( 
    { _id: fromUserId }, 
    { $pullAll: { linkedUsers: [idToDelete] } }, 
    { new: true }, 
    function(err, data) {} 
);

or

User.findByIdAndUpdate(fromUserId, 
    { $pullAll: { linkedUsers: [idToDelete] } }, 
    { new: true }, 
    function(err, data) {} 
);
like image 115
chridam Avatar answered Oct 13 '22 20:10

chridam


I had a similar issue. I wanted to delete an object from an array, using the default _id from mongo, but my query was wrong:

const update = { $pull: { cities: cityId }};

It should be:

const update = { $pull: { cities: {_id: cityId} }};
like image 5
Juliana Miranda Avatar answered Oct 13 '22 20:10

Juliana Miranda