Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

mongodb - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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) {} 
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...